How do I trigger something from a widget button?

2019-07-15 20:19发布

问题:

No matter what I do I cannot trigger anything by clicking on a button on a widget. Here is some code I wrote, can anyone tell me why onReceive isn't called when the widget button is clicked?

Furthermore, I want to run a function on button click... based on the code below do I have the right idea?

public class WidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        Intent intent = new Intent(context, WidgetProvider.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setOnClickPendingIntent(R.id.toggleButton, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds[0], views);

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // why don't i get here with the button click?
        Log.e("!", intent.getAction());
    }
}

回答1:

Try to call the super method of onReceive first.

 @Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    // why don't i get here with the button click?
    Log.e("!", intent.getAction());
}

Worked just fine for me!