我有一个 Android 服务,是使用 StartService() 在应用程序的第一个 Activity 的 OnCreate 中创建的。我需要此服务在应用程序的整个生命周期中运行,即应用程序中的所有活动。但在用户按下主页键或后退按钮后,服务不应消耗资源。除了在所有活动的 onPause() 方法中停止服务之外,还有什么优雅的方法可以做到这一点吗?
您可以在onResume中调用bindService并在onPause中调用unbindService,而不是使用StartService。当没有打开的绑定时,您的服务将停止。
您需要创建一个 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)