0

I am writing a small widget that contains 2 buttons. The problem is - occasionally, when the widget is removed/added to the screen, the buttons doesn't work, seems that they don't have any listener attached. I use the code below in my BroadcastReceiver :

@Override
public void onUpdate(final Context context, final AppWidgetManager aAppWidgetManager,
                     final int[] appWidgetIds) {
    super.onUpdate(context, aAppWidgetManager, appWidgetIds);
    Log.d("Widget_On_update", "Total widgets : " + appWidgetIds.length);
    for (final int widgetId : appWidgetIds) {
        Log.d("Widget_On_update", "Updating widget : " + widgetId);
        final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        updateActionListener(true, context, appWidgetIds, remoteViews, UPDATE_DATA_ACTION, id.button_data_update);
        updateActionListener(true, context, appWidgetIds, remoteViews, UPDATE_WIFI_ACTION, id.button_wifi_update);
        aAppWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
    updateStatus(context);
}


private void updateActionListener(final boolean add, final Context context, final int[] appWidgetIds,
                                  final RemoteViews aRemoteViews, final String aAction, final int aViewId) {
    // Register an onClickListener
    final Intent intent = new Intent(context, DataToggleWidgetProvider.class);
    intent.setAction(aAction);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (add) {
        aRemoteViews.setOnClickPendingIntent(aViewId, pendingIntent);
    } else {
        pendingIntent.cancel();
    }
}

I tried different values for the second parameter of PendingIntent.getBroadcast, such as Math.random, a static counter and so on. Neither of these ways worked. Can anyone help me ?

Thank you in advance.

StKiller
  • 7,631
  • 10
  • 43
  • 56

1 Answers1

2

Have you checked that onUpdate() is being executed on your widgets after rebooting? You might want to consider invoking an update through onEnabled(). See this answer to a related question.

Community
  • 1
  • 1
Paul Lammertsma
  • 37,593
  • 16
  • 136
  • 187