我有一个具有绑定服务的单例对象。我希望它重新启动,当我从启动器启动应用程序时,单例对象将初始化并绑定到这个现有的服务实例。
以下是在单例中创建和绑定服务的代码:
public class MyState {
private static MyState sState;
private MyService mService;
private Context mContext;
private boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder binder = (MyService.MyBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
public static MyState get(Context context) {
if (sState == null) {
sState = new MyState(context);
}
return sState;
}
public MyState(Context context) {
mContext = context.getApplicationContext();
startService();
}
private void startService() {
Intent intent = new Intent(mContext, MyService.class);
mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// this won't create another instance of service, but will call onStartCommand
mContext.startService(intent);
}
}
这是 Service 中的代码
public class MyService extends Service {
private final IBinder mBinder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// this method is called by singleton object to stop service manually by user
public void stop() {
stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
// some cleanup code here
}
}
不幸的是,当我在任务列表中滑动我的应用程序时,该服务永远不会重新启动。在这种情况下,永远不会调用 Service 的 onDestroy 方法。
我将绑定移至用户可以与服务交互的活动,令人惊讶的是它开始按我的预期工作。
我尝试使用活动中的应用程序上下文调用服务创建,它仍然有效。
从 Activity 启动服务与从常规 java 对象启动服务不同吗?