【问题标题】:How to check for Proximity Alerts and find them如何检查接近警报并找到它们
【发布时间】:2017-05-14 13:29:03
【问题描述】:

我有一个关于接近警报的问题。 在我读过的所有教程中,它们是在创建它们的活动仍在运行时创建和销毁的。 但是,如果说一个活动创建了 n 个接近警报然后活动本身被销毁(PA 没有)会发生什么

如果我想构建另一个活动来找到这些接近警报,我该怎么做?这甚至可能吗?

【问题讨论】:

    标签: android proximity


    【解决方案1】:

    您必须维护自己的接近警报列表。没有办法让他们回来。但是,@Mercato 是正确的,他说您可以仅使用未决意图删除 PA,但您不必存储它们。根据文档:

    PendingIntent 本身只是对系统维护的令牌的引用,该令牌描述了用于检索它的原始数据。这意味着,即使它拥有的应用程序的进程被杀死,PendingIntent 本身仍可用于其他已给予它的进程。如果创建应用程序稍后重新检索相同类型的 PendingIntent(相同的操作、相同的 Intent 操作、数据、类别和组件以及相同的标志),它将收到一个表示相同令牌的 PendingIntent,如果它仍然有效,并且可以因此调用 cancel() 将其删除。

    这意味着系统将在应用程序重新启动之间为您存储您的PendingIntent,您可以通过传递用于创建它的相同Intent 来检索它。例如,如果您创建了以下PendingIntent

    Intent intent = new Intent(context, Foo.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    

    那么您只需要存储requestId (1) 和Class 或类名(Foo.classFoo.class.getName())。然后,如果您想检索相同的PendingIntent 而不创建新的,您可以执行以下操作:

    Class<Foo> className = retrieveClass(); //You implement this
    //String clazz = retrieveClassName(); //This is another option
    int requestId = retrieveId(); //You implement this
    
    Intent intent = new Intent(context, className);
    
    //The flag given attempts to retrieve the PendingIntent if it exists, returns null if it doesn't.
    PendingIntent pi = PendingIntent.getBroadcast(context, requestId, intent, PendingIntent.FLAG_NO_CREATE);
    if (pi != null) {
        //This pending intent was registered once before. 
        //Go ahead and call the function to remove the PA. Also, go ahead and call pi.cancel() on this.
    }
    else {
        //This pending intent was not registered, and therefore can't have a PA registered to it. 
    } 
    

    【讨论】:

    • 非常好,谢谢!我明白你的解释,我只有一个问题。文档说“..same flags”,但在代码中 PendingIntent.FLAG_UPDATE_CURRENT 已被 FLAG_NO_CREATE 取代。我认为这是有道理的,但它不与文档相矛盾吗?
    • 我相信你在谈论传递给pendingintent的意图,这会有所作为。 FLAG_NO_CREATE 是一个pendingintent 标志,通知操作系统不要创建新的pendingintent。 FLAG_UPDATE_CURRENT 将使用您的意图中提供的新额外内容更新待处理的意图,只要该意图与旧意图相同,或者创建一个新的待处理意图。
    【解决方案2】:

    从技术上讲,所有接近警报都需要定义 PendingIntent 并将其用作参数。 Android's Documentation 表明如果您知道PendingIntents 的列表,那么您也可以删除它们。

    removeProximityAlert(PendingIntent intent) 移除接近警报 使用给定的 PendingIntent。

    由于PendingIntentParecelable see here,那么您可以将其作为Extra 添加到任何Intent。这意味着,在启动另一个 Activity 时,您可以创建一个 Parcelable[] 数组来保存所有这些 PendingIntent,然后

    putExtra(String name, Parcelable[] value) 向 Intent 添加扩展数据。

    然后通过getIntent() 及其相关方法在下一个活动中检索它们。

    【讨论】:

    • 谢谢。根据您的解释,我知道如果我在 Activity A 中创建 PA,然后从 Activity A 调用 Activity B,然后 PA 被 Activity B 销毁,对吗?换句话说,从 A 幕到 B 幕的过渡,我错了吗?我的意思更多是因为 A 幕和 B 幕是不相关的......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多