NFC通讯机制如下图:
代码详解:
public class MainActivity extends Activity {
private boolean isSupportNfc = true ;
private NfcAdapter nfcAdapter ;
private PendingIntent pendingIntent ;
private String info = "";
private IntentFilter[] mFilters ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initNfc();
}
@Override
protected void onResume() {
super.onResume();
if(isSupportNfc){
startNFCListener();
}
}
@Override
protected void onPause() {
super.onPause();
stopNFCListener();
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private void initNfc() {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if(nfcAdapter == null){
isSupportNfc = false ;
info = "该台设备不支持NFC功能";
showToast(info);
return;
}
if(!nfcAdapter.isEnabled()){
isSupportNfc = false ;
info = "请在系统设置中启动NFC功能";
showToast(info);
return;
}
//Intent的启动模式为Intent.FLAG_ACTIVITY_SINGLE_TOP时,如果该Activity已经处于顶部,则会调用onNewIntent方法
pendingIntent = PendingIntent.getActivity(this,0,new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
/**
* 三重过滤机制
* ndef:只过滤固定格式的NDEF数据。例如:纯文本、指定协议(http、ftp、smb等)的URI等
* tech:这种过滤机制并不是通过Tag中的数据格式进行匹配的,而是根据Tag支持的数据存储格式进行匹配,因此这种过滤机制的范围更广
* tag: 这种过滤机制用来处理未识别的Tag(数据格式不对,而且Tag支持的格式也不匹配)。
*/
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mFilters = new IntentFilter[] { ndef, tech, tag };
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//校验intent
processIntent(intent);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private void processIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
System.out.println(tag);
System.out.println(HEX.bytesToHex(tag.getId()));//输出NFC卡id
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private void startNFCListener() {
// 开始监听NFC设备是否连接,如果连接就发PendingIntent意图
nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters, null);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private void stopNFCListener() {
// 停止监听NFC设备是否连接
nfcAdapter.disableForegroundDispatch(this);
}
private void showToast(String info) {
Toast.makeText(this,info,Toast.LENGTH_SHORT).show();
}
}
nfc权限:
<uses-permission android:name="android.permission.NFC" />