简体   繁体   English

如何在活动从任务切换器中清除后阻止服务重新启动?

[英]How to prevent service from restarting after activity is swept from task switcher?

I have this question about services in Android, and how to prevent immediate restart of the service if the activity is swept away in task manager ( when you hold home button). 我有关于Android中的服务的问题,以及如果活动在任务管理器中被清除(如果您按住主页按钮),如何防止立即重启服务。

I want a service to be persistent and have it's own process and memory image, so when my activity shut's down, in this case swept away from task switcher, the service won't restart... 我想要一个服务是持久的并拥有它自己的进程和内存映像,所以当我的活动关闭时,在这种情况下从任务切换器中扫除,服务将不会重新启动...

Could anybody show me some tutorials and sites explaining how to solve this problem? 有人能给我看一些解释如何解决这个问题的教程和网站吗?

Put your service in a separate process as follows: 将您的服务放在单独的流程中,如下所示:

Go to your service declaration in the android manifest and change it to: 转到Android清单中的服务声明并将其更改为:

<service android:name=".ServiceName" android:process=":remote" />

NOTE: 注意:

Because your service is running in a separate process you must switch processes in your LogCat (if using Android Studio) to view your debug logs. 由于您的服务在单独的进程中运行,因此您必须在LogCat中切换进程(如果使用Android Studio)以查看调试日志。

Services are designed to restart in the background when destroyed (this is a broad statement, there are many factors), so to ensure this doesn't happen: 服务被设计为在销毁时在后台重启(这是一个广泛的声明,有很多因素),所以要确保不会发生这种情况:

Either create a bound service that is created and destroyed with the calling activity: 创建使用调用活动创建和销毁的绑定服务

This example is taken from the docs 此示例取自文档

public class LocalService extends Service {
    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

Or run the service in the foreground , so that when it is removed from the foreground it is destroyed. 或者在前台运行服务,这样当它从前台移除时就会被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM