文章目录
最近在获通过NfcAdapter.aenableForegroundDispatch发现不能正确调度使用android.nfc,后来发现是Adnroid12以后PendingIntent的新特性导致。
在代码中使用的是PendingIntent.FLAG_IMMUTABLE,此标志创建的PendingIntent是不可变的,而FLAG_MUTABLE是可变的。
将FLAG_IMMUTABLE 替换为 FLAG_MUTABLE即可,在Android12以后需要主要PendingIntent的Flag细节和模式。
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private void initNfc() {
mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
mPendingIntent = PendingIntent.getActivity(activity, 0,
new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);
}
private void nfcEnabled() {
if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
mNfcAdapter.enableForegroundDispatch(activity, mPendingIntent, intentFilters, techLists);
}
}
以下是这两种Flag的区别:
Android官方文档:https://developer.android.com/reference/android/app/PendingIntent
public static final int FLAG_MUTABLE = 1<<25;
标志,表示创建的PendingIntent应该是可变的。该标志不能与FLAG_IMMUTABLE组合使用。
直到Build.VERSION_CODES。R中,默认情况下PendingIntents是可变的,除非设置了FLAG_IMMUTABLE。从Build.VERSION_CODES开始。S,它需要在创建时显式指定PendingIntents的可变性(@link #FLAG_IMMUTABLE}或FLAG_MUTABLE。强烈建议在创建PendingIntent时使用FLAG_IMMUTABLE。FLAG_MUTABLE应该只在某些功能依赖于修改底层意图时使用,例如,任何PendingIntent需要与内联回复或气泡一起使用。
public static final int FLAG_IMMUTABLE = 1<<26;
标志,表示创建的PendingIntent应该是不可变的。这意味着传递给send方法用来填充未填充属性的额外intent参数将被忽略。
FLAG_IMMUTABLE只限制了send()的调用者改变send()发送的意图语义的能力。PendingIntent的创建者总是可以通过FLAG_UPDATE_CURRENT来更新PendingIntent本身。