安卓的onCreate服务调用时,活动的onDestroy被称为 [英] Android onCreate Service called when Activity onDestroy called

查看:222
本文介绍了安卓的onCreate服务调用时,活动的onDestroy被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动的服务活动。如果我退出到主界面,然后从最近的应用程序列表中手动关闭该活动的onCreate是在服务再次调用。

I have an activity that starts a service. If I exit to home screen and then from the recent apps list manually close the activity, onCreate is called again in the service.

因此​​,当活动被破坏,的onCreate再次调用(即使该服务,则对当时的onDestroy运行被称为在活动)

So when the activity is destroyed, onCreate is called again (even though the service was running at the time onDestroy was called in the activity)

我不想的onCreate在被再次调用该服务。我知道它的这种可能的重复:<一href="http://stackoverflow.com/questions/7211066/android-service-oncreate-is-called-multiple-times-without-calling-ondestroy">Android服务的onCreate被多次调用,而不调用的onDestroy 但在这里把服务于其他进程无法正常工作(至少在Android 4.4奇巧)的建议的解决方案

I don't want onCreate in the service to be called again. I know its a possible duplication of this: Android service onCreate is called multiple times without calling onDestroy BUT the solution suggested here of putting the service in another process doesn't work (at least on Android 4.4 kit kat)

有什么建议?

推荐答案

这是因为杀死后,从最近使用的应用程序列表中的应用程序,你强行杀死服务。有两种方法,以避免重新启动。不那么伟大的方式是把服务在不同的过程比Android清单活动。

This is because upon killing the application from the "recently used apps" list, you're killing the service by force. There are two ways to avoid restart. The not so great way is to put the service in different process than the activity in the Android Manifest.

例如:

<activity ...
     process:"com.example.activity.process" />
 <service ...
     process:"com.example.service.process" />

于是在查杀服务还没有被杀死并重新启动应用程序。该服务将Android作为它,如果你去通过这种方法认为合适的终止。

So upon killing the application the service is also not killed and restarted. The service will be terminated by Android as it sees fit if you go by this method.

更正确的方法是使用 onStartCommand()方法。

The more correct way would be to use the onStartCommand() method.

只需添加以下code为您服务:

Simply add the following code to your service:

@Override
public int onStartCommand(Intent intent, int flags, int startID) {
    return START_NOT_STICKY;
}

这将prevent服务被重新启动,如果没有正确端接即的onDestroy()不叫。

This will prevent the service from being restarted if improperly terminated i.e onDestroy() is not called.

这篇关于安卓的onCreate服务调用时,活动的onDestroy被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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