【问题标题】:Create new Pending Intent every time in Android每次在 Android 中创建新的 Pending Intent
【发布时间】:2013-02-24 05:12:09
【问题描述】:

如何每次都创建待处理的 Intent?目前,我现有的待定意图正在被新的意图所取代。我尝试使用FLAG_ONE_SHOTCANCEL_CURRENT,但没有成功。

【问题讨论】:

    标签: android android-pendingintent


    【解决方案1】:

    像这样在请求代码中添加一个随机数:

    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);
    

    【讨论】:

    • 您最好使用当前时间戳,因为它保证每秒都不同。一个随机数可以重复...不过你需要转换为一个 int:(int)(System.currentTimeMillis()/1000)
    • 在计算机领域,一秒的长度是巨大的,我想说随机数不太可能重复!
    • @mxcl 是的,“计算机领域”要大得多。但这不是计算机领域。 ing0 是对的,加上时间戳会更好。
    • Random 做得很好。谢谢,
    • ' PendingIntent.getBroadcast(Context, rand, Intent, int) ' 也这样吗?
    【解决方案2】:

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

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

    FLAG_ONE_SHOT - 此 PendingIntent 只能使用一次。

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

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

    【讨论】:

    • 那是为了通知。我说的是待定意图。每次它都应该创建新的 Intent。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2015-12-19
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    相关资源
    最近更新 更多