应用程序关闭时重新启动服务 - START_STICKY

RuA*_*are 8 service android

我有一个作为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);
}
Run Code Online (Sandbox Code Playgroud)

服务开始

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, START_STICKY, startId);
    Log.d("SERVICE","Started");
    return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

Mim*_*oli 9

简短的回答:你做不到.当系统声明内存或用户从最近的应用列表中清除应用时,每个Android应用都可能被系统或用户杀死.这是Android设计,所有应用都必须遵守它.您可以获得的唯一(小)改进是将服务设置为Foreground服务:

系统认为它是用户积极意识到的东西,因此在内存不足时不是杀人的候选者.(从理论上讲,服务在当前前台应用程序的极端内存压力下被杀死仍然是可能的,但实际上这不应该是一个问题.)