我试图检测何时单击了小部件按钮,但没有任何 Intent 附加项显示在 onReceive 方法中。
onReceive 每次点击都会被调用,但我的 Intent 额外内容没有出现。

我的代码如下:我只在更新时连接切换按钮,所以不确定这是否正确。即使我设置了这个,也没有任何额外内容出现并且类别是 null

onUpdate(上下文上下文等):

RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                                R.layout.my_widget);

Intent buttonIntent = new Intent(context, MyWidgetProviderClass.class);
buttonIntent.setAction(ACTION_WIDGET_RECEIVER);
buttonIntent.putExtra("BUTTON_CLICKED", "buttonClick");
buttonIntent.putExtra("BUTTON",899);

PendingIntent muPendingIntent = PendingIntent.getBroadcast(context, 0,
                                        buttonIntent,
                                        PendingIntent.FLAG_CANCEL_CURRENT);
buttonIntent.addCategory("buttonclick");
remoteViews.setOnClickPendingIntent(R.id.ToggleImageButton, myPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

onReceive():
intent.getIntExtra("BUTTON",-1);    ---> 1
intent.getCategories()   --- > null

最佳答案

尝试 FLAG_UPDATE_CURRENT 而不是 FLAG_CANCEL_CURRENT

此外,您的代码可能有一个错字:您使用的是 muPendingIntent 而不是 myPendingIntent

另外,请不要使用 buttonclick 作为类别。请命名它(例如 com.something.whatever.buttonclick ),或将其删除,因为我不确定您为什么需要它。

Here is a sample project 演示了一个应用小部件,它在单击时触发自身更新,并带有额外的(用于提供应用小部件 ID)。

关于android - 在 onReceive 中找不到按钮单击发送的 WidgetProvider Intent extras,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5022868/

10-11 19:17