0

我正在编写一个包含 2 个按钮的小部件。问题是 - 有时,当小部件被删除/添加到屏幕时,按钮不起作用,似乎它们没有附加任何监听器。我在 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();
    }
}

我为PendingIntent.getBroadcast的第二个参数尝试了不同的值,比如Math.random,一个静态计数器等等。这些方法都不起作用。谁能帮我 ?

先感谢您。

4

1 回答 1

2

您是否检查过onUpdate()重启后正在您的小部件上执行的操作?您可能需要考虑通过onEnabled(). 请参阅相关问题的此答案。

于 2012-04-15T14:54:39.270 回答