android - 在 onReceive 中找不到随按钮单击发送的 WidgetProvider Intent extras

标签 android widget android-intent broadcastreceiver

我正在尝试检测何时单击小部件按钮,但 onReceive 方法中没有显示任何 Intent extra。

onReceive 会在每次点击时调用,但我的 Intent extras 都不会出现。

我的代码如下:我只在更新时连接切换按钮,所以不确定这是否正确。即使我设置了这个,也没有额外显示并且类别为 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/

相关文章:

java - 如何在android中的另一个类中调用带有View类型参数的函数

android - 如何获得计数列

android - Facebook Sdk 版本和支持 :appcompat version issue

javascript - 使用 react.js 聊天小部件

java - 跟踪 Android 上的应用程序

java - 语音识别器声音

android - 打开 native 电话簿作为 Intent 并将其用于搜索。可能的?

android - 在 Android 项目中使用 Gradle 解决依赖项时出错

Facebook 按钮在 Firefox 和 Chrome 上呈现不同

android - 如何最大化 Android 小部件尺寸(宽度)?