編輯:關於 Android 程式設計
近場通訊(NFC)讓手機能直接感應卡片,因此在門禁、工牌打卡、資產盤點這類應用裡非常實用。本文以一個最小可用範例,示範如何在 Android 中取得感應到的卡片 UID(卡號)。
先在 AndroidManifest.xml 中申請 NFC 權限,並以 uses-feature 標明需要 NFC 硬體:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="true" />
若希望 App 未開啟時也能被卡片感應唤起,可在目標 Activity 上加入 intent-filter:
<intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED" /> <data android:mimeType="text/plain" /> </intent-filter>
取得 NfcAdapter 並建立 PendingIntent。當有卡片靠近時,系統會把 Intent 直接交給目前的 Activity 處理:
//初始化NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // 初始化PendingIntent,當有NFC設備連接上的時候,就交給當前Activity處理 pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
在 onResume() 中啟用 foreground dispatch,確保 App 位於前台時優先接收 NFC 事件:
@Override protected void onResume() { super.onResume(); mNfcAdapter.enableForegroundDispatch(this, pi, null, null); //啟動 }
App 在前台時,系統會改走 onNewIntent() 回呼,因此只需在此判斷 Action 是否為 NFC 相關即可:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 當前app正在前端界面運行,這個時候有intent發送過來,那麼系統就會調用onNewIntent回調方法,將intent傳送過來 // 我們只需要在這裡檢驗這個intent是否是NFC相關的intent,如果是,就調用處理方法 if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { processIntent(intent); } }
從 Intent 中取出 Tag 物件,再將 getId() 回傳的位元組陣列轉成十六進位字串,就是我們熟悉的卡號:
/** * 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); String CardId =ByteArrayToHexString(tagFromIntent.getId()); } private String ByteArrayToHexString(byte[] inarray) { int i, j, in; String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; String out = ""; for (j = 0; j < inarray.length; ++j) { in = (int) inarray[j] & 0xff; i = (in >> 4) & 0x0f; out += hex[i]; i = in & 0x0f; out += hex[i]; } return out; }
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.jslh.zjcdprogrect"> <uses-permission android:name="android.permission.NFC" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-feature android:name="android.hardware.nfc" android:required="true" /> <application android:name=".common.MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".saoka.WorkActivity"> <intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED" /> <data android:mimeType="text/plain" /> </intent-filter> <!--<meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfc_tech_filter" />--> </activity> </application> </manifest>
WorkActivity.java:
package cn.com.jslh.zjcdprogrect.saoka; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import cn.com.jslh.zjcdprogrect.R; public class WorkActivity extends AppCompatActivity { private NfcAdapter mNfcAdapter; private PendingIntent pi; private IntentFilter tagDetected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_work); //初始化NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this); //初始化PendingIntent // 初始化PendingIntent,當有NFC設備連接上的時候,就交給當前Activity處理 pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); // 新建IntentFilter,使用的是第二種的過濾機制 // tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); // tagDetected.addCategory(Intent.CATEGORY_DEFAULT); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 當前app正在前端界面運行,這個時候有intent發送過來,那麼系統就會調用onNewIntent回調方法,將intent傳送過來 // 我們只需要在這裡檢驗這個intent是否是NFC相關的intent,如果是,就調用處理方法 if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { processIntent(intent); } } @Override protected void onResume() { super.onResume(); mNfcAdapter.enableForegroundDispatch(this, pi, null, null); } /** * 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); String CardId =ByteArrayToHexString(tagFromIntent.getId()); } public static void startActivity(Context context){ Intent intent = new Intent(); intent.setClass(context,WorkActivity.class); context.startActivity(intent); } private String ByteArrayToHexString(byte[] inarray) { int i, j, in; String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; String out = ""; for (j = 0; j < inarray.length; ++j) { in = (int) inarray[j] & 0xff; i = (in >> 4) & 0x0f; out += hex[i]; i = in & 0x0f; out += hex[i]; } return out; } }
實作時要特別留意兩點:一是 enableForegroundDispatch 必須在 onPause() 中成對地以 disableForegroundDispatch 關閉,避免資源洩漏;二是部分機型或卡片型別(如 MIFARE 系列)的 UID 長度為 4、7 或 10 位元組,轉字串時需先確認長度再作後續比對。
Android 背景圖片縮放動畫實作解析
有些視覺效果希望背景圖片能慢慢放大,但控制項本身大小不變。這時不能直接縮放 View,而應該對圖片本身進行縮放繪製。 實作原理 首先取得要顯示的圖片,接著建立一份副本。然
Android Gesture 手勢識別用法詳解
本文透過實例分析 Android 中 Gesture 手勢識別的用法,分享給大家參考,具體如下: 很高興能在 Android 1.6 的 SDK 中看到手勢識別這個功能。
Cordova 自定義插件開發完整流程解析
環境準備開發 Cordova 自定義插件前,需要先準備 Node.js、Cordova 命令列工具與 Android SDK。安裝完成後,可透過 npm 與 cordov
Android 如何用 AIDL Service 傳遞自訂的複雜物件
在 Android 中透過 AIDL 可以跨進程呼叫 Service 的資料,網路上的範例不少,但絕大多數只示範基本型別的遠端呼叫,很少觸及複雜物件。本文就用一個完整例子