CL So CL So - 1 year ago 69
Android Question

Why Android app crash when close app if I getExtras in Service?


I start a service

Intent serv=new Intent(this, MyService.class);
serv.putExtra("mac", "mac");

In the service, I get the parameter

public int onStartCommand(Intent intent, int flags, int startId) {
String mac=intent.getExtras().getString("mac");
return super.onStartCommand(intent, flags, startId);

Then I kill the app, the app will crash, and the service will also crash.

If I remove this line, then it will be no problem, the service also alive after I killed the app.

String mac=intent.getExtras().getString("mac");

Why the app crash?

Answer Source

super.onStartCommand(intent, flags, startId) returns the START_STICKY flag by default which, according to the docs, mean that:

"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."

Since the Intent isn't being redelivered you likely get NPE when calling intent.getExtras().

To redeliver the Intent return the START_REDELIVER_INTENT flag from onStartCommand():

public int onStartCommand(Intent intent, int flags, int startId) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download