PendingIntent 中的一个新 PendingIntent 字段是 FLAG_IMMUTABLE。
在31中,必须指定MUTABLE或IMMUTABLE,否则不能创建PendingIntent,(当然我们不能有默认值,那是给loser的)引用here
根据(热闹的)Google Javadoc for Pendingintent,您基本上应该始终使用 IMMUTABLE(empasis mine):
It is strongly recommended to use FLAG_IMMUTABLE when creating a PendingIntent. FLAG_MUTABLE should only be used when some functionality relies on modifying the underlying intent, e.g. any PendingIntent that needs to be used with inline reply or bubbles (editor's comment: WHAT?).
对,所以我总是为这样的地理围栏创建 PendingIntents:
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE)
一直工作得很好。但是,按照上面的文档,我添加了 IMMUTABLE 标志,如下所示:PendingIntent proximityIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_IMMUTABLE)
现在,结果是,虽然我仍然在接收器中进行地理围栏转换,但如果我打电话
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
它返回空!所以,我有两个问题。
其实我有三个问题:
非常感谢指针。
最佳答案
在这种情况下,地理围栏的待定 Intent 需要使用 FLAG_MUTABLE
而通知待处理 Intent 需要使用FLAG_IMMUTABLE
.不幸的是,他们没有更新 documentation或 codelabs example还针对 Android 12。以下是我修改 codelabs 地理围栏示例以使其工作的方式。
首先,将 gradle 更新为目标 SDK31。
在 HuntMainActivity
,更改geofencePendingIntent
至:
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceBroadcastReceiver::class.java)
intent.action = ACTION_GEOFENCE_EVENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
} else {
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
在 NotificationUtils.kt
,更新通知待定 Intent ,如下所示: val contentIntent = Intent(context, HuntMainActivity::class.java)
contentIntent.putExtra(GeofencingConstants.EXTRA_GEOFENCE_INDEX, foundIndex)
val contentPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.getActivity(
context,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
} else {
PendingIntent.getActivity(
context,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
关于android - 在 Android 12/API 31 中,地理围栏不适用于 IMMUTABLE 未决 Intent 。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69615196/