【发布时间】:2015-08-01 08:32:00
【问题描述】:
我有一个作为 Web 服务器运行的应用程序。该应用程序有一项服务是 START_STICKY 我希望此服务始终运行 Web 服务器(在通知中为用户提供停止它的选项)。
问题是当我关闭我的应用程序时服务器重新启动(丢失设置等)。它保持在那里很好,但 logcat 显示它正在重新启动。
我可以重新打开我的应用程序并绑定到新服务,这工作正常。虽然再次滑动关闭具有相同的效果。
我需要这个不要重新启动。
标准服务代码
private WebServerService mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder binder) {
WebServerService.MyBinder b = (WebServerService.MyBinder) binder;
mService = b.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
public serviceStart() {
mIntent = new Intent(mContext.getApplicationContext(), WebServerService.class);
mContext.startService(mIntent);
mContext.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
}
服务启动
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, START_STICKY, startId);
Log.d("SERVICE","Started");
return START_STICKY;
}
【问题讨论】:
-
看看@fedepaol 的这个答案 [Android 后台服务在应用程序被杀死时重新启动][1] [1]:*.com/questions/15452935/…
-
这不是我想要的,它说的是根本不希望它重新启动!我希望它甚至不接近。不过谢谢,我认为这是我解绑后的东西。
-
您的服务可以并且将会被系统杀死,您对此无能为力。但是,如果你有开始粘性,你会以一个空意图再次开始。重启后你必须恢复你的状态。
-
能否提供启动服务的代码?常量 START_STICKY 意味着服务应该在关闭后重新启动。如果您不希望它在关闭后重新启动,那么 START_NOT_STICKY 将是合适的