环境 android studio 2022 sdk 33
刚刚开始我的代码是这样的,结果给我的 提示 接收到的Intent不是由NFC触发的 我很蒙圈为什么然后我见过我调试 我发现 我改 里面的那个
public class MainActivity extends AppCompatActivity {
private static final String TAG = "NfcWriteActivity";
private NfcAdapter nfcAdapter;
private TextView mTvName;
public static IntentFilter[] mIntentFilter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvName = findViewById(R.id.textView);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "不支持NFC功能", Toast.LENGTH_SHORT).show();
return;
}
if (!nfcAdapter.isEnabled()) {
Toast.makeText(this, "请打开NFC功能", Toast.LENGTH_SHORT).show();
Intent inten = new Intent(Settings.ACTION_NFC_SETTINGS);
// 根据包名打开对应的设置界面
startActivity(inten);
return;
}
}
@Override
protected void onResume() {
super.onResume();
try {
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter filter3 = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
String[][] techList = new String[][]{new String[]{NfcA.class.getName()}, {Ndef.class.getName()}, {MifareUltralight.class.getName()}};
mIntentFilter = new IntentFilter[]{filter, filter2, filter3};
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 10, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, mIntentFilter, techList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
try {
nfcAdapter.disableForegroundDispatch(MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
String action = intent.getAction();
if (!NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) &&
!NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) &&
!NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
Log.e(TAG, "");
Toast.makeText(this, "接收到的Intent不是由NFC触发的", Toast.LENGTH_SHORT).show();
return;
}
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMe