Launching activity from widget

后端 未结 9 1167
深忆病人
深忆病人 2020-11-29 00:26

I\'m trying to do something which really ought to be quite easy, but it\'s driving me crazy. I\'m trying to launch an activity when a home screen widget is pressed, such as

9条回答
  •  暖寄归人
    2020-11-29 01:04

    Bringing this way back from the dead, but I had a similar problem and I think I finally solved it... like you, I had a PendingIntent that I attached to the RemoteView. Sometimes it would work, and sometimes it would fail. It was driving me crazy.

    What I found from a tooltip on the PendingIntent.getActivty() was:

    Note that the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.

    so, I added:

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    

    No example code I've seen so far does this, but it solved my problem; the Settings activity is now launched reliably.

    The full code that's working well...

    Intent intent = new Intent(context, Settings.class);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);  // Identifies the particular widget...
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // Make the pending intent unique...
    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
    PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wwwidget);
    views.setOnClickPendingIntent(R.id.widget, pendIntent);
    appWidgetManager.updateAppWidget(appId,views);
    

提交回复
热议问题