我有一个服务,当活动开始时,我用以下方式绑定到服务:
bindService(new Intent(BaseActivity.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);这条路对吗?
我需要服务将启动时,应用程序启动,并生活在后台模式始终。如果用户在设置中手动停止应用程序,那么当应用程序再次启动时,服务也需要启动。
如果服务已经存在,我不需要创建它(已经在后台模式下运行)。有一个正确的方式绑定到现有的服务?
有人知道我能用正确的方式做这件事吗?
提前感谢!
发布于 2014-12-10 13:32:22
1.只需启动像这样的无界服务
startService(new Intent(BaseActivity.this, MyService.class));2.在被OS杀死时自动重新启动您的服务
在您的onStartCommand()返回START_STICKY中
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}3.设置按钮停止
在onDestroy() of Service中再次启动服务,如
@Override
public void onDestroy() {
// starting the service when the service is destroyed.
Intent intent = new Intent(this, YourService.class);
startService(intent);
super.onDestroy();
};注意:如果您在设置中FORCE_STOP应用程序,服务将停止
https://stackoverflow.com/questions/27402148
复制相似问题