javaandroidandroid-widgetandroid-appwidget

Android AppWidgetProvider onReceive not called on button click


I have a widget running under android and I would like for it to update itself when the user clicks a button on the widget.

For some reason, the onReceive method is never called when a button is clicked after i install the widget.

I have a onUpdate method like this in my AppWidgetProvider class:

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

        super.onUpdate(context, appWidgetManager, appWidgetIds);

        for (int i = 0; i < appWidgetIds.length; ++i) {

              final RemoteViews rv = 
new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);       

              final Intent nextIntent = 
new Intent(context, TestAppWidgetProvider.class);
              nextIntent.setAction(TestAppWidgetProvider.NEXT_ACTION);
              nextIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);

              final PendingIntent refreshPendingIntent = 
PendingIntent.getBroadcast(context, 0,
                                nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
              rv.setOnClickPendingIntent(R.id.next, refreshPendingIntent);

              appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
         }
}

And then in my on receive i have a method that looks like:

@Override
public void onReceive(Context ctx, Intent intent) {

    super.onReceive(ctx, intent);

    final String action = intent.getAction();

    if (action.equals(PREV_ACTION)) {

        Toast.makeText(ctx, "Previous clicked..", Toast.LENGTH_SHORT).show();
    } else if (action.equals(NEXT_ACTION)) {

        Toast.makeText(ctx, "Next was clicked..", Toast.LENGTH_SHORT)
                .show();
    }
    else {
        Toast.makeText(ctx, "Other action..", Toast.LENGTH_SHORT).show();
    }           
}

I have this in my manifest file too:

<receiver android:name="com.test.android.widget.TestAppWidgetProvider" >
      <intent-filter >
          <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
      </intent-filter>
      <intent-filter >
          <action android:name="com.test.android.widget.PREV" />
      </intent-filter>
      <intent-filter >
          <action android:name="com.test.android.widget.NEXT" />
      </intent-filter>
      <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/appwidget_info" />
</receiver>

After I install the widget and click on the next button, the onReceive method is never called for some reason...


Solution

  • Fixed it, turned out to be trivial.

    It was because onReceive wasn't even being called on widget creation, so the event listener wasn't setup.

    Added some of the code that was in onReceive (setting the setOnClickPendingIntent etc) to a function which is called when the widget configure activity is ready to update the widget.