下面是步骤:
1.获取管理权限:这个开发包里已经集成了,只需要调用一句代码就可以搞定,这个还是挺方便的。
PermissionUtil.grantNeedPermission(this);
2.打开NFC,并监听NFC事件,这段如果不懂,直接在网上搜安卓使用NFC就可以看到介绍
private NfcAdapter mAdapter = null; // 定义NFC适配器
mAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);//.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
mTechLists = new String[][]{new String[]{NfcB.class.getName()}, new String[]{NfcA.class.getName()}};
if (mAdapter != null && !mAdapter.isEnabled()) {
Toast.makeText(this, "NFC尚未开启", Toast.LENGTH_SHORT).show();
}
3.因为我的NFC事件是在子线程中的,所以new了一个handle
private static class MyHandler extends Handler {
private final WeakReference<IDCardScannerActivity> mActivity;
public MyHandler(IDCardScannerActivity activity) {
mActivity = new WeakReference<IDCardScannerActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
System.out.println(msg);
if (mActivity.get() == null) {
return;
}
if (msg.what == 1002)