5

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?

Bardya Momeni
  • 337
  • 4
  • 13

2 Answers2

0

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.

petey
  • 16,914
  • 6
  • 65
  • 97
Mohsin Ali
  • 381
  • 3
  • 8
0

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.

petey
  • 16,914
  • 6
  • 65
  • 97