Settings Activity Not Launching

2019-02-28 16:01发布

问题:

So far i have coded:

public class WidgetActivity extends AppWidgetProvider
{    
    public void onReceive(Context context, Intent intent)
    {


        String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
        {

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_activity);

            Intent settingsIntent = new Intent(context, Info.class);
            PendingIntent clickPendIntent = PendingIntent.getActivity
                    (context, 0, settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.Widget, clickPendIntent);





            AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);


        }
    }
}

To no success i click the widget when its on screen and nothing launches. Am I missing anything?

回答1:

Put the code that makes sure the PendingIntent is set, in the onUpdate() method instead. This makes sure that as soon as the widget is put on the homescreen that the PendingIntent is set.

So:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgets) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_activity);
    Intent intent = new Intent(context, Info.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.Widget, pendingIntent);

Also:

If you would also like to have the info Activity pop up automatically when first adding the widget to the home screen, you should read this userful piece of information.