服务在应用程序关闭时重新启动-START_STICKY [英] Service restarted on Application Close - START_STICKY

查看:51
本文介绍了服务在应用程序关闭时重新启动-START_STICKY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可作为网络服务器运行的应用程序.该应用程序提供的服务是START_STICKY,我希望该服务一直运行该Web服务器(在通知用户停止该服务的选项).

I have an app that runs as a web server. The app has a service that is START_STICKY I want this service to run the web server all the time (option is given to user in a notification to stop it).

问题是当我关闭我的应用程序时,服务器会重新启动(丢失设置等).它在那里保持良好状态,但logcat显示它正在重新启动.

Problem is that the server is restarted (loosing settings etc) when i swipe my app closed. It stays there fine but logcat shows that it is restarting.

我可以重新打开我的应用程序并绑定到新服务,这可以正常工作.尽管再次滑动关闭具有相同的效果.

I can re- open my app and bind to the new service, this works fine. Although swipe closing again has the same effect.

我需要此操作才能不重新启动.

I need this to NOT restart.

标准服务代码

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设计,所有应用都必须遵守.您唯一可以做的改进是将服务设置为

Short answer: you can't. Every Android app can be killed by the system or by the user when the system claims memory or the user swipes out the app from the recent apps list. This is an Android design and all apps must adhere to it. The only (small) improvement you can have is setting the service as a Foreground service:

系统认为它是用户积极了解的东西,因此在内存不足时不是杀死的候选者.(从当前的前台应用来看,从理论上讲,仍然有可能在极高的内存压力下终止该服务,但实际上,这不必担心.)

where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

这篇关于服务在应用程序关闭时重新启动-START_STICKY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆