NFC的出现让移动平台充满了幻想,ios还没有支持,但是android平台已经成了旗舰机的必备功能,很有幸公司的项目中也用到了NFC,只是从特定的NFC卡里面读取一个卡的ID,每个应用只能有一个NFC入口,所以当一个应用多出用到NFC功能跳转的话,只能写在一个Activity中,解析到数据后决定往哪里跳。下面就给出代码:
首先是AndroidManifest中对NFC的Activity的配置
<activity
android:name=".NFCActivity"
android:configChanges="screenSize|keyboardHidden|orientation"
android:launchMode="singleTask"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
</activity>
nfc_tech_filter.xml
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
</resources>
然后是NFCActivity
/**
* NFC响应页面
*
* @author Jinyang
*
*/
public class NFCActivity extends BaseActivity {
public static final String TAG = "NFCActivity";
private NfcAdapter nfcAdapter;
private String mClientCardNfcId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc);
initNfcParse();
}
private void initNfcParse() {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
AppContext.showLog("---->Nfc error !!!");
Toast.makeText(getApplicationContext(), "不支持NFC功能!",
Toast.LENGTH_SHORT).show();
} else if (!nfcAdapter.isEnabled()) {
AppContext.showLog("---->Nfc close !!!");
Toast.makeText(getApplicationContext(), "请打开NFC功能!",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onResume() {
super.onResume();
AppContext.showLog("---->onDestroy");
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
Tag tagFromIntent = getIntent().getParcelableExtra(
NfcAdapter.EXTRA_TAG);
MifareClassic mfc = MifareClassic.get(tagFromIntent);
try {
mfc.connect();
byte[] byteId = mfc.getTag().getId();
String nfcId = StringUtils.hexToHexString(byteId);
if (!nfcId.isEmpty()) {
mClientCardNfcId = nfcId;
AppContext.showLog("卡的内容" + mClientCardNfcId
);
} else {
Toast.makeText(this, "识别失败!请重新刷卡!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
AppContext.showLog("error = " + e.getMessage());
e.printStackTrace();
}
}
}
}
工具类解析:
public static String hexToHexString(byte[] b) {
int len = b.length;
int[] x = new int[len];
String[] y = new String[len];
StringBuilder str = new StringBuilder();
int j = 0;
for (; j < len; j++) {
x[j] = b[j] & 0xff;
y[j] = Integer.toHexString(x[j]);
while (y[j].length() < 2) {
y[j] = "0" + y[j];
}
str.append(y[j]);
str.append("");
}
return new String(str).toUpperCase(Locale.getDefault());
}
NFC与现有非接触智能卡技术兼容,目前已经成为得到越来越多主要厂商支持的正式标准。有了NFC通过手机能够获取非电子设备的信息是不是充满了幻想,生活中有太多这样的需求,手机应用强大的可自定义的数据分析功能,加上NFC简单方便的获取信息能力,我感觉有很多东西又要发生革新了。