Android AppWidgetProvider在按钮点击时未被调用的问题

4

我有一个在安卓系统下运行的小部件,我希望当用户点击小部件上的按钮时它可以自动更新。

但是,在我安装了小部件之后,无论用户点击哪个按钮,onReceive方法都从未被调用过。

我在我的AppWidgetProvider类中有一个如下所示的onUpdate方法:

@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);
         }
}

然后在我的onReceive方法中,我有一个类似以下的方法:

@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();
    }           
}

我也在我的清单文件中添加了这个:
<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>

安装了小部件并点击下一个按钮后,由于某种原因onReceive方法从未被调用...

1个回答

2

问题已解决,原来很简单。

因为在小部件创建时onReceive甚至没有被调用,所以事件监听器没有被设置。

将一些在onReceive中的代码(例如设置setOnClickPendingIntent等)添加到一个函数中,在小部件配置活动准备更新小部件时调用该函数。


5
你能分享你的解决方案吗? - earlymorningtea

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