简体   繁体   中英

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).

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:

<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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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