Activity使用NFC
一、声明全局变量
声明全局变量:PendingIntent 和 NfcAdapter
PendingIntent 说明:PendingIntent可以看作是对Intent的一个封装,但它不是立刻执行某个行为,而是满足某些条件或触发某些事件后才执行指定的行为。
PendingIntent详解:https://blog.csdn.net/hudashi/article/details/7060837
private PendingIntent pendingIntent;
//Nfc适配器
private NfcAdapter nfcAdapter;
二、给NFC适配器赋值
在onCreate方法中对nfcAdapter 进行赋值。
nfcAdapter.isEnabled()返回值为false时表示NFC未启动。
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter != null&&nfcAdapter.isEnabled()){
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
三、NFC的前台调度
在onResume方法中启用
Enable foreground dispatch to the given Activity.
启用对给定Activity的前台调度。
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null&&nfcAdapter.isEnabled()) {
if (pendingIntent ==null){
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
在onPause方法中禁用
Disable foreground dispatch to the given activity.
禁用对给定Activity的前台调度。
@Override
protected void onPause() {
super.onPause();
if (null != nfcAdapter&&nfcAdapter.isEnabled()) {
nfcAdapter.disableForegroundDispatch(this);
}
}
三、NFC刷卡事件处理
在onNewIntent方法中获取NFC调度事件
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String action = intent.getAction();
if (!EmptyUtil.isEmpty(action)){
if (NfcAdapter.ACTION_TECH_DISCOVERED.equalsIgnoreCase(action) ||
NfcAdapter.ACTION_TAG_DISCOVERED.equalsIgnoreCase(action) ||
NfcAdapter.ACTION_NDEF_DISCOVERED.equalsIgnoreCase(action)) {
try {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
MifareClassic mifareClassic = MifareClassic.get(tag);
if (mifareClassic!=null) {
mifareClassic.connect();
if (!mifareClassic.isConnected()){
Log.w(TAG,"卡连接失败");
return;
}
//获取卡的物理卡号
String CardId=StringUtil.byteToHex(mifareClassicard.getTag().getId());
Log.i(TAG,CardId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
四、注意事项
在项目的AndroidManifest.xml 文件添加对NFC硬件的使用权限。
<!--外部存储读取权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--外部存储写入权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--允许设备访问NFC硬件-->
<uses-permission android:name="android.permission.NFC" />
有问题处,还请指出感激不尽。
参考资料:
https://blog.csdn.net/qq_36135335/article/details/82463179
https://blog.csdn.net/hudashi/article/details/7060837
https://developer.android.google.cn/reference/android/nfc/NfcAdapter