In my Android app I have a service which should be restarted automatically after it gets killed. I found out that this can be done using START_STICKY
.
But apparently when the service is automatically restarted, the intent is null
. The problem however, is that the intent is used to pass along a value. See the example below:
public class MyService extends Service {
public static final String MY_STRING_HANDLE = "MyString";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Read my string from intent
Bundle extras = intent.getExtras(); // ERROR: Intent can be null
if (extras == null) {
throw new Error("Intent did not contain my string");
}
String myString = extras.getString(MY_STRING_HANDLE);
if (myString == null || myString.isEmpty()) {
throw new Error("Intent did not contain my string");
}
// Do something with my string
doSomeThing(myString);
return START_STICKY;
}
}
So usually I start the service like this:
Intent intent = new Intent(activity, MyService.class);
intent.putExtra(MyService.MY_STRING_HANDLE, "Example string");
activity.startService(intent);
This works, but when the service is killed and automatically restarted I get the following result:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
So my question is: If I cannot use intents, then how should I pass on values (i.e. myString
) to my service?
Regarding possible duplicate: My question is not about why the intent is null
, it's about how I can handle this.