mahdi
mahdi

Reputation: 16407

prevent service restarting in android

i try to use service in my android application but i have a problem. when i press turn on/off button after screen lock the service run with interrupt, it`s look like service is restarting. this is my code :

public class MyService extends Service {
private static String TAG = "Service";

@Override
public void onCreate() {
  super.onCreate();
  Log.i(TAG, "onCreate");

}

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

@Override
public void onDestroy() {
  Log.i(TAG, "Destroyed");
  super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Log.i(TAG, "OnStartcommmand");
  return START_STICKY;
 }

 }

Why My service restart many time ? how can i prevent from service restarting ? is it possible ? thanks

Upvotes: 1

Views: 1029

Answers (1)

TOP
TOP

Reputation: 2614

Your Service is killed by System to save resources for higher priority apps (for example: when phone runs out of memory). After being killed, your Service can be recreated depending on the value returned on onStartCommand. If you return START_STICKY on onStartCommand, System will recreate you service after killing it. Otherwise, START_NOT_STICKY tells the OS to not bother recreating the service again.

You can consider to use startForeground method to keep your Service alive. Here is the documentation:

A started service can use the startForeground(int, Notification) API to put the service in a foreground state, 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.)

Upvotes: 4

Related Questions