我有一个 Android 服务,它是在应用程序的第一个 Activity 的 OnCreate 中使用 StartService() 创建的。我需要此服务在应用程序的整个生命周期内运行,即应用程序中的所有 Activity 。但服务不应在用户按下 Home 键或后退按钮后消耗资源。除了在所有 Activity 的 onPause() 方法中停止服务之外,还有什么优雅的方法可以做到这一点吗?
最佳答案
您可以在 onResume 中调用 bindService,在 onPause 中调用 unbindService,而不是使用 StartService。当没有打开的绑定(bind)时,您的服务将停止。
您需要创建一个 ServiceConnection 才能访问该服务。例如,这里有一个嵌套在 MyService 中的类:
class MyService {
public static class MyServiceConnection implements ServiceConnection {
private MyService mMyService = null;
public MyService getMyService() {
return mMyService;
}
public void onServiceConnected(ComponentName className, IBinder binder) {
mMyService = ((MyServiceBinder)binder).getMyService();
}
public void onServiceDisconnected(ComponentName className) {
mMyService = null;
}
}
// Helper class to bridge the Service and the ServiceConnection.
private class MyServiceBinder extends Binder {
MyService getMyService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return new MyServiceBinder();
}
@Override
public boolean onUnbind(Intent intent) {
return false; // do full binding to reconnect, not Rebind
}
// Normal MyService code goes here.
}
可以使用此助手类通过以下方式访问服务:
MyServiceConnection mMSC = new MyService.MyServiceConnection();
// Inside onResume:
bindService(new Intent(this, MyService.class), mMSC, Context.BIND_AUTO_CREATE);
// Inside onPause:
unbindService(mMSC);
// To get access to the service:
MyService myService = mMSC.getMyService();
关于按 Home 键后运行的 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4273539/