Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: detect restarted service with START_REDELIVER_INTENT flag

Tags:

android

My widget has a service attached to it to process various click "commands" which are passed through its intent. I've also set return START_REDELIVER_INTENT; for the case of when the service is restarted to not give a nullPointerException when calling intent.getAction(); and the like. The problem is, when the last intent was sent by one of the setOnClickPendingIntent calls I have, then when the service is restarted, it acts as if the user had clicked one of the viewId's. e.g.

String command = intent.getAction();
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
if(command.equals("some command")){
    //do something
}

...

remoteView.setOnClickPendingIntent(R.id.viewId,MyClass.makeControlPendingIntent(getApplicationContext(),"some command",appWidgetId));

Where makeControlPendingIntent is:

public static PendingIntent makeControlPendingIntent(Context context, String command, int appWidgetId) {
        Intent active = new Intent(context,MyService.class);
        active.setAction(command);
        active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        Uri data = Uri.withAppendedPath(Uri.parse("myclass://widget/id/#"+command+appWidgetId), String.valueOf(appWidgetId));
        active.setData(data);
        return(PendingIntent.getService(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT));
    }

Is there something I can do to check if the service is being restarted so as to not run any of those commands in the case where Android restarts my service?

like image 362
aperture Avatar asked Oct 17 '11 21:10

aperture


1 Answers

Is there something I can do to check if the service is being restarted so as to not run any of those commands in the case where Android restarts my service?

The flags parameter to onStartCommand() will contain START_FLAG_REDELIVERY if the Intent is being re-delivered. So, you can do something like this:

public int onStartCommand(Intent intent, int flags, int startId) {
    if ((flags & START_FLAG_REDELIVERY)!=0) { // if crash restart...
        // do something here
    }

    // rest of logic here
}
like image 196
CommonsWare Avatar answered Oct 10 '22 02:10

CommonsWare