昨天同事找我帮忙看看 rfid 开发的时候,一扫描就直接弹出activity的问题。
网上也有蛮多例子,但是能直接拿来参考写实际项目的没几个,系统提供的demo呢,一扫描标签就弹出activity,也是开发中不想要的。于是进入苦逼模式,进过分析和翻资料、百度、终于解决了。下面是代码:
先看项目图片, 我是直接用demo修改的:
1、清单文件:
需求添加权限啦什么,自己看啊,
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nl.nfcdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15" /> <!-- 添加nfc权限 --> <uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.nl.nfcdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
2、MainAcivity类。
package com.nl.nfcdemo;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String ACTION_NAME = "android.nfc.action.TECH_DISCOVERED";
NfcAdapter nfcAdapter;
TextView promt;
private PendingIntent mPendingIntent;
private IntentFilter [] mIntentFilters;
private String[][] mTechLists;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
promt = (TextView) findViewById (R.id.promt);
// 获取默认的NFC控制器
nfcAdapter = NfcAdapter.getDefaultAdapter (this);
if (nfcAdapter == null) {
promt.setText ("设备不支持NFC!");
finish ();
return;
}
if (!nfcAdapter.isEnabled ()) {
promt.setText ("请在系统设置中先启用NFC功能!");
finish ();
return;
}
initNFC();
}
/**
*@Description: 初始化
*@Author:杨攀
*@Since: 2016年4月27日下午5:38:15
*/
private void initNFC(){
//绑定Intent
Intent mIntent = new Intent (ACTION_NAME);
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter techFilter = new IntentFilter (nfcAdapter.ACTION_TECH_DISCOVERED);
try {
techFilter.addDataType ("text/plain");
mIntentFilters = new IntentFilter[]{techFilter};
} catch (MalformedMimeTypeException e) {
e.printStackTrace();
}
mTechLists = new String[][] {
new String[] {"android.nfc.tech.NfcA"},
new String[]{"android.nfc.tech.NfcB"},
new String[]{"android.nfc.tech.NfcF"},
new String[]{"android.nfc.tech.NfcV"},
new String[]{"android.nfc.tech.Ndef"},
new String[]{"android.nfc.tech.NdefFormatable"},
new String[]{"android.nfc.tech.IsoDep"},
new String[]{"android.nfc.tech.MifareClassic"},
new String[]{"android.nfc.tech.MifareUltralight"}
};
}
/**
*@Description: 拦截系统的 intent, 然后触发读写操作
*@Author:杨攀
*@Since: 2016年4月27日下午5:08:20
*@param intent
*/
@Override
protected void onNewIntent(Intent intent){
super.onNewIntent (intent);
// 得到是否检测到ACTION_TECH_DISCOVERED触发
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals (intent.getAction ())) {
// 处理该intent
processIntent (intent);
}
}
/**
*@Description: 注册 意图
*@Author:杨攀
*@Since: 2016年4月27日下午5:34:21
*/
@Override
protected void onResume(){
super.onResume ();
nfcAdapter.enableForegroundDispatch (this, mPendingIntent, mIntentFilters, mTechLists);
}
/**
*@Description: 窗口关闭的时候,注销意图
*@Author:杨攀
*@Since: 2016年4月27日下午5:34:35
*/
@Override
protected void onPause(){
super.onPause ();
//注销注册
nfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onDestroy(){
super.onDestroy ();
}
// 字符序列转换为16进制字符串
private String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder ("0x");
if (src == null || src.length <= 0) { return null; }
char[] buffer = new char[2];
for ( int i = 0 ; i < src.length ; i++ ) {
buffer[0] = Character.forDigit ((src[i] >>> 4) & 0x0F, 16);
buffer[1] = Character.forDigit (src[i] & 0x0F, 16);
System.out.println (buffer);
stringBuilder.append (buffer);
}
return stringBuilder.toString ();
}
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
private void processIntent(Intent intent){
// 取出封装在intent中的TAG
Tag tagFromIntent = intent.getParcelableExtra (NfcAdapter.EXTRA_TAG);
for ( String tech : tagFromIntent.getTechList () ) {
System.out.println (tech);
}
boolean auth = false;
// 读取TAG
MifareClassic mfc = MifareClassic.get (tagFromIntent);
String metaInfo = "本标签的UID为" + Coverter.getUid (intent) + "\n";
if (mfc != null) {
try {
// Enable I/O operations to the tag from this TagTechnology
// object.
mfc.connect ();
int type = mfc.getType ();// 获取TAG的类型
int sectorCount = mfc.getSectorCount ();// 获取TAG中包含的扇区数
String typeS = "";
switch (type) {
case MifareClassic.TYPE_CLASSIC:
typeS = "TYPE_CLASSIC";
break;
case MifareClassic.TYPE_PLUS:
typeS = "TYPE_PLUS";
break;
case MifareClassic.TYPE_PRO:
typeS = "TYPE_PRO";
break;
case MifareClassic.TYPE_UNKNOWN:
typeS = "TYPE_UNKNOWN";
break;
}
metaInfo += "卡片类型:" + typeS + "\n共" + sectorCount + "个扇区\n共" + mfc.getBlockCount () + "个块\n存储空间: " + mfc.getSize () + "B\n";
for ( int j = 0 ; j < sectorCount ; j++ ) {
// Authenticate a sector with key A.
auth = mfc.authenticateSectorWithKeyA (j, MifareClassic.KEY_DEFAULT);
int bCount;
int bIndex;
if (auth) {
metaInfo += "Sector " + j + ":验证成功\n";
// 读取扇区中的块
bCount = mfc.getBlockCountInSector (j);
bIndex = mfc.sectorToBlock (j);
for ( int i = 0 ; i < bCount ; i++ ) {
byte[] data = mfc.readBlock (bIndex);
metaInfo += "Block " + bIndex + " : " + bytesToHexString (data) + "\n";
bIndex++;
}
} else {
metaInfo += "Sector " + j + ":验证失败\n";
}
}
} catch (Exception e) {
e.printStackTrace ();
}
}
promt.setText (metaInfo);
}
}
经过运行,可以。我在上传 项目的压缩包。需要的自行下载。