每次在Android中创建新的Pending Intent

Chi*_*tan 17 android android-pendingintent

如何每次创建待处理的意图?目前,我现有的待定意图将被替换为新的意图.我尝试使用FLAG_ONE_SHOT,CANCEL_CURRENT但它没有用.

Zee*_*v G 33

在请求代码中添加一个随机数,如下所示:

Intent intent = new Intent(context, YourClassname.class);
intent.putExtra("some data", "txt");  // for extra data if needed..

Random generator = new Random();

PendingIntent i=PendingIntent.getActivity(context, generator.nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)

  • 你最好使用当前的时间戳,因为每秒都保证不同.一个随机数_could_重复...你需要强制转换为int:`(int)(System.currentTimeMillis()/ 1000)` (10认同)
  • 在计算机领域,一秒的长度是巨大的,我会说随机数不太可能重复! (7认同)

Tam*_*thu 11

FLAG_CANCEL_CURRENT-如果描述的PendingIntent已经存在,则在生成新的PendingIntent之前取消当前的PendingIntent.

FLAG_NO_CREATE - 如果描述的PendingIntent尚不存在,则只返回null而不是创建它.

FLAG_ONE_SHOT - 此PendingIntent只能使用一次.

FLAG_UPDATE_CURRENT-如果描述的PendingIntent已经存在,那么保留它,但是它用这个新Intent中的内容替换它的额外数据.

如果您确实需要多个不同的PendingIntent对象同时处于活动状态(例如用作同时显示的两个通知),那么您需要确保有一些不同的东西将它们与不同的关联起来PendingIntents.这可以是所考虑的任何Intent属性Intent.filterEquals,或者提供给它的不同请求代码整数getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).