Widget + ListView + TaskStackBuilder -> BroadcastReceiver 找不到

Widget + ListView + TaskStackBuilder -> BroadcastReceiver won't get found

我已经为这个疯狂了。

因此,我创建了一个带有 ListView 的小部件。在列表视图中的每个项目上,我都想有一个简单的按钮,'calls' 一个带有特定参数的 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 中,我只是创建一个带有 BroadcastReceiver 参数的 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 明确需要 activity。但我不想在点击时启动 Activity。

我想通了。

val myPendingIntentTemplate = PendingIntent.getBroadcast(context, 0, myIntentTemplate, PendingIntent.FLAG_UPDATE_CURRENT)

我以前试过,但似乎从来没有用过。真正的问题是 AVD 模拟器,它随机决定工作和不工作(广播有时不传送)。

如果您需要开发这样的小部件,请在真实设备上进行。