我有一个可作为网络服务器运行的应用程序。该应用程序具有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;
}
简短答案:您不能。当系统要求内存或用户从最近的应用程序列表中刷出该应用程序时,每个Android应用程序都可能被系统或用户杀死。这是一个Android设计,所有应用都必须遵守。您唯一可以做的(小)改进就是将服务设置为前台服务:
系统认为它是用户主动意识到的东西,因此在内存不足时不是杀死的对象。(从当前的前台应用来看,从理论上讲,仍然有可能在极高的内存压力下终止该服务,但实际上,这不必担心。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句