小部件ImageButton监听器并不总是被调用

5
我有一个简单的小部件(Android 2.1),它只包含一个LinearLayout,其中包含一个ImageButton。 ImageButton具有on-click监听器。 问题是:如果我在主屏幕上放置几个相同的小部件,则有些正常工作(按下按钮时调用监听器),而有些则不行! 我无法看出哪些可以工作,哪些不行。
以下是小部件布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null">

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ImageButton01"
    android:src="@drawable/widget_running"
    android:background="@null">
</ImageButton>

以下是小部件提供程序的代码:

public class GPAppWidgetProvider extends AppWidgetProvider {
private String mTag = getClass().getSimpleName();

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;
    Log.e(mTag, "onUpdate ");

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        Log.e(mTag, "widget onUpdate one loop");
        int appWidgetId = appWidgetIds[i];

        // Create an Intent
        Intent intent = new Intent(context, GPService.class).setAction(ACTION_WIDGET_TOGGLE_PAUSE);
        intent.putExtra("widgetId", appWidgetId);
        PendingIntent pauseIntent = PendingIntent.getService(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gp_appwidget);
        views.setOnClickPendingIntent(R.id.ImageButton01, pauseIntent);

        // widget update
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

}


一个更新:看起来如果我重新启动手机或应用程序,所有的小部件都能正常工作…但是如果我添加新的小部件,大多数情况下它们不会工作,直到我重新启动手机或重启应用程序... - Gael
我也遇到了这个问题,一旦我添加了主屏幕小部件,它不会立即将监听器附加到按钮上。我必须通过主屏幕图标运行服务/启动应用程序来触发更新。 - setzamora
1个回答

0

我遇到了同样的问题。

在调用“getService”时,请不要忘记设置不同的“requestCode”:

public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)

请确保每个小部件的“appWidgetId”都不同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接