Search code examples
androidkotlinandroid-widgetandroid-broadcastreceiver

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


I'm going crazy over this already.

So, I created a widget with a ListView. On each item in the listview I wanted to have a simple button, which 'calls' a BroadcastReceiver with a certain parameter.

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
}

Manifest

<receiver
    android:name=".MyReceiver"
    android:enabled="true"
    android:exported="true">
</receiver>

In the RemoteViewsFactory I'm simply creating a FillInIntent with the parameter for the BroadcastReceiver and adding it as a OnClickFillInIntent to my button. This works fine, since the widget gets created and loaded. But when I click on the buttons I get this error:

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)

So, basically it says it doesn't find com.mydomain.myapp/.MyReceiver.

I'm quite sure that my mistake is whilst creating the intent. Also, the PendingIntent explicitly wants an activity. But I don't want to start an Activity on click.


Solution

  • I figured it out.

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

    I tried that before, but it never seemed to work. The real issue was the AVD Emulator, which randomly decided to work and not to work (the Broadcasts where sometimes not delivered).

    If you need to develop a widget like that, do it on a real device.