【问题标题】:Android RequestLocationUpdates to pendingItent with extra bundle带有额外捆绑包的 Android RequestLocationUpdates 到 pendingItent
【发布时间】:2016-07-29 07:42:28
【问题描述】:

我在接收位置更新时触发了一个 BoradcastReceiver

 PendingIntent pendingIntent = PendingIntent
          .getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
      LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
          mLocationRequest, pendingIntent); 

还有我的接收器

 public static class LocationReceiver extends BroadcastReceiver {

@Override
    public void onReceive(Context context, Intent intent) {
      boolean hasLocation = LocationResult.hasResult(intent);
    }
}

如果我运行上面的代码,一切正常,hasLocation 总是正确的,完美的。

但如果我想将一些变量传递给接收器,我会这样做:

Intent intent = ..
intent.putExtra("test", "hello");
PendingIntent pendingIntent = PendingIntent
              .getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);

现在位在接收方 LocationResult.hasResult(intent);总是假的

这是一个错误吗?有解决方法吗?如何将变量传递给接收方?

【问题讨论】:

  • hasResult 是返回真还是假?
  • 当我没有在 Intent 中添加任何额外内容时,hasResult 返回 TRUE
  • 你说 hasResult 总是 NULL,但它返回一个布尔值。是真的还是假的?如果您确实在意图中添加了额外内容
  • 很抱歉给您带来了困惑。我的意思总是错误的。
  • 如果你记录额外的意图,你会得到什么?

标签: android android-intent service location broadcastreceiver


【解决方案1】:

我在谷歌搜索时发现了您的问题。我会分享我的解决方案,以防其他人像我一样发现这个问题。

首先,这是我的情况,和你的情况类似:

requestLocationUpdates() 将位置数据存储在意图的 mExtras 字段中。出于某种原因,如果我使用 Intent.putExtra() 向 Intent 添加另一个 Extra,则不会添加位置数据。所以 onHandleIntent() 被调用,但意图是缺少位置数据。如果我不添加任何 Extras,那么位置数据就会通过,一切都很好。

我的解决方法:

我使用 Intent.addCategory() 和 getCategory() 来做与 putExtra("myExtraName", String) 完全相同的事情。如果要传递其他数据类型,请将它们转换为字符串,然后在 onHandleIntent() 中解析它们。

我的环境:

我正在使用 Play Services 版本 11.0.4 和 FusedLocationProviderClient,因为 FusedLocationProviderApi 最近已被弃用。 FusedLocationProviderClient.requestLocationUpdates() 文档似乎没有解决这个问题。

【讨论】:

  • 文档没有解决这个问题。但它似乎仍然存在同样的问题。我刚碰到它,在这里找到了这个。
  • 使用 addCategory 只有一个问题(或不同)。那是在调用“removeLocationUpdates”时。有了附加功能,它们将被忽略。对于类别,类别必须相同。因此,只有在创建具有相同类别的完全相同的 PendingIntent 时才能取消。
猜你喜欢
  • 2014-01-08
  • 1970-01-01
  • 2015-09-21
  • 2012-03-30
  • 2019-02-06
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多