Question

I have an activity, in its OnCreate:

    serviceIntent = new Intent(this, MyServ.class);
    int templen =  myString.length();
    Log.i("check", "mystring"+templen);     
    serviceIntent.putExtra("myString", myString);       
    startService(serviceIntent);

In the service,

public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub      
    myString = intent.getExtras().getString("myString");
    return START_STICKY;
}

It works fine. Then i opened many apps, to make android closes my app/services to free some ram. As you may expect, with START_STICKY, the service will try to restart, however, it failed to restart. The error log is:

Caused by: java.lang.NullPointerException at com.example.myapp.myserv.onStartCommand(MyServ.java:77), which points to this line:

myString = intent.getExtras().getString("myString");

So what i believe is there is no intent sent from myact when the service restarted. How should I handle this case? thanks

Was it helpful?

Solution

If you return START_STICKY, the documentation says:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

If, instead of START_STICKY, you return START_REDELIVER_INTENT, the documentation says:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).

So, it sounds to me like you either need to return START_STICKY and understand that on a restart onStartCommand() will be called with a null Intent object or you need to return START_REDELIVER_INTENT and understand that if your service is not currently executing the onStartCommand() method when it is killed that it won't be restarted at all.

If you need to save the most recent value of myString, you can write this to shared preferences.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top