Catster
Catster

Reputation: 23

Android onStartCommand flags

I have a simple service:

public class TestService extends Service {

final String LOG_TAG = "myLogs";

public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "TestService onCreate");
}

public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "TestService onDestroy");
}

public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "TestService onStartCommand")
    readFlags(flags);
    MyRun mr = new MyRun(startId);
    new Thread(mr).start();
    return START_REDELIVER_INTENT;
}

public IBinder onBind(Intent arg0) {
    return null;
}

void readFlags(int flags) {
    switch (flags) {
        case START_FLAG_REDELIVERY:
            Log.d(LOG_TAG, "START_FLAG_REDELIVERY");
            break;
        case START_FLAG_RETRY:
            Log.d(LOG_TAG, "START_FLAG_RETRY");
            break;
        default:
            Log.d(LOG_TAG, "Flag: " + flags);
    }
}

class MyRun implements Runnable {

    int startId;

    public MyRun(int startId) {
        this.startId = startId;
        Log.d(LOG_TAG, "Run#" + startId + " create");
    }

    public void run() {
        Log.d(LOG_TAG, "Run#" + startId + " start");
        try {
            TimeUnit.SECONDS.sleep(15);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stop();
    }

    void stop() {
        Log.d(LOG_TAG, "Run#" + startId + " end, stopSelfResult("
                + startId + ") = " + stopSelfResult(startId));
    }
}

If I understand correctly, flag START_REDELIVER_INTENT should restart my service as soon, as there is sufficient memory available. But (I've checked it on 3 devices (4.1.2, 4.4.2 and 6.0.1)) when I kill the proc, the service restarts on only 1 of them (4.1.2):

 D/myLogs: TestService onCreate
 D/myLogs: TestService onStartCommand
 D/myLogs: START_FLAG_REDELIVERY
 D/myLogs: MyRun#1 create
 D/myLogs: MyRun#1 start
 D/myLogs: MyService onDestroy
 D/myLogs: MyRun#1 end, stopSelfResult(1) = true

What's the problem with two other devices? Same problem with other flags, e.g. START_STICKY - service proc dies permanently.

Upvotes: 2

Views: 1981

Answers (1)

RahulDeep Attri
RahulDeep Attri

Reputation: 418

Override onLowMemory() method and put Log.d Tag also there, it would tell you when OS will try to stop service in a resource crunch.

START_REDELIVER_INTENT- tells the system to restart the service after the crash and also redeliver the intents that were present at the time of crash. Crash could be because of low resources.

If resource crunch does not happens then, your activity would not be stopped by OS.

Upvotes: 2

Related Questions