Widget sending multiple types of intents

让人想犯罪 __ 提交于 2019-11-29 08:48:21
Muthu Selvam

you need to provide seperate request code for each pendingintent ex:

PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); 
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 1/*request code*/, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

Your PendingIntents are being overwritten by the next one. THis is because they compare the Intent being encapsulated, and extras are not considered when comparing Intents. Do this for each intent:

Intent intent1 = new Intent("myapp.SendWidgetPreset");
intent1.putExtra("Widget", 1);

// This line makes your intents different
intent1.setData(Uri.parse(intent1.toUri(Intent.URI_INTENT_SCHEME)));

PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.widgetPreset1Button, pendingIntent1);

Seems like PendingIntent.getBroadcast() will ignore requestCode (unlike PendingIntent.getActivity).

Thus, to make unique PendingIntents you could supply Data for the Intent.

Example:

public static Intent makeUniqueIntent(String action, int requestCode) {
        Intent intent = new Intent(action);
        intent.setData(Uri.parse("http://"+ String.valueOf(requestCode)));
        return intent;
    }

Then make your Pending Intent as per usual, including the requestCode.

PendingIntent.getBroadcast(ctx, request_code,
                makeUniqueIntent(NotificationReceiver.INTENT, request_code),
                PendingIntent.FLAG_CANCEL_CURRENT);

With a Data element in an Intent, a matching Intent Filter within AndroidManifest.xml must also have a Data element:

<receiver android:name=".service.NotificationReceiver">
       <intent-filter>
           <action android:name="my.package.my_action_string"/>
           <data android:scheme="http"/>
       </intent-filter>
</receiver>

The above intent-filter works as only a scheme (i.e. "http") was identified. So any Uri with that scheme will match this filter's "data" element and the corresponding Receiver class will be called.

Notes:

  • NotificationReceiver is my class, extending BroadcastReceiver
  • NotificationReceiver.INTENT is a String constant I declared in NotificationReceiver. In this example it would equal "my.package.my_action_string";
  • request_code can be anything. Make it unique & save it if you want to reference this same Pending Intent in the future (say for canceling an alarm that uses it).

More info on Data test with Intent Filters:

http://developer.android.com/guide/components/intents-filters.html#DataTest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!