问题描述
我已经为此疯狂了。
因此,我使用ListView创建了一个小部件。 我希望在列表视图中的每个项目上都有一个简单的按钮,该按钮“调用”具有特定参数的BroadcastReceiver。
的AppWidgetProvider
override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) {
// Getting the RemoteView, setting adapter etc
val myIntentTemplate = Intent(context, MyReceiver::class.java)
val myPendingIntentTemplate = TaskStackBuilder.create(context)
.addParentStack(MainActivity::class.java)
.addNextIntent(myIntentTemplate)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
remoteViews.setPendingIntentTemplate(R.id.listview, myPendingIntentTemplate)
// Updating app widget
}
表现
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
</receiver>
在RemoteViewsFactory
我只是使用FillInIntent
的参数创建FillInIntent
,并将其作为OnClickFillInIntent
添加到我的按钮中。
由于小部件已创建并加载,因此效果很好。
但是,当我单击按钮时,出现此错误:
09-15 01:53:02.160 1961-3674/system_process I/ActivityManager: START u0 {flg=0x1000c000 cmp=com.mydomain.myapp/.MyReceiver bnds=[864,524][984,596] (has extras)} from uid 10119
09-15 01:53:02.160 2581-2581/com.google.android.apps.nexuslauncher E/RemoteViews: Cannot send pending intent due to unknown exception:
android.content.ActivityNotFoundException: No Activity found to handle null
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
at android.app.Activity.startIntentSenderForResultInner(Activity.java:4845)
at android.app.Activity.startIntentSenderForResult(Activity.java:4812)
at com.android.launcher3.Launcher.startIntentSenderForResult(SourceFile:1356)
at android.app.Activity.startIntentSender(Activity.java:4997)
因此,基本上它说找不到com.mydomain.myapp/.MyReceiver
。
我非常确定我的错误是在创建意图时。 另外,PendingIntent明确想要一个活动。 但我不想在单击时启动活动。
1楼
我想到了。
val myPendingIntentTemplate = PendingIntent.getBroadcast(context, 0, myIntentTemplate, PendingIntent.FLAG_UPDATE_CURRENT)
我之前曾尝试过,但似乎从未奏效。 真正的问题是AVD模拟器,它随机决定起作用而不起作用(有时无法发送广播)。
如果您需要开发这样的小部件,请在实际设备上进行。