NFC,什麼是NFC?想必你們都聽過,就是近場通訊,接下來我想給你們展現一個簡單的demo, 這個demo是我在公司工做中開發的功能.但願這篇文章對你們有所幫助java
目前在市場在見得比較多的電子標籤有 1443 和15693 兩種類型的卡片(固然還有其它類型的),這兩種卡片是什麼東東呢?本身百度一下,網上一大把資料有介紹的.
android
在我實際開發過程當中就是主要接觸這兩種類型的卡片.我須要實現的功能是,利用帶有NFC功能的手機,去讀取電子標籤中的數據(卡片id值這裏叫UID),網上能夠下載不少能夠讀取電子標籤的app軟件,可是,在個人demo裏面, 是要屏蔽第三方的NFC掃描軟件, 我只想用本身開發的軟件去讀取這些電子標籤(即不使用前臺調度,彈出個對話框,讓咱們選擇使用哪一個NFC軟件去讀取)app
很少說, 直接上源碼比較實在ide
package com.iotdc.android.app.nfc.activity; import java.io.Serializable; import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.graphics.Paint; import android.nfc.NfcAdapter; import android.nfc.NfcManager; import android.nfc.tech.IsoDep; import android.nfc.tech.MifareClassic; import android.nfc.tech.MifareUltralight; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.nfc.tech.NfcA; import android.nfc.tech.NfcB; import android.nfc.tech.NfcF; import android.nfc.tech.NfcV; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.iotdc.android.app.scanner.R; import com.iotdc.android.app.scanresult.activity.TwoDimensionCodeActivity; import com.iotdc.android.app.utils.NFCUtil; import com.iotdc.android.app.utils.NFCUtil.NFCData; @SuppressLint("NewApi") public class NFCActivity extends Activity { // private Intent intent; private TextView tvNfc; private TextView tvOpenNfC; private NfcManager manager; private NfcAdapter adapter; private PendingIntent mNfcPendingIntent; private IntentFilter[] mWriteTagFilters; private String[][] techListsArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc); initTitile(); init(); initNFC(); } private void init() { tvNfc = (TextView) findViewById(R.id.tv_nfc); tvOpenNfC = (TextView) findViewById(R.id.tv_open_nfc); tvOpenNfC.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); tvOpenNfC.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(NFCActivity.this, NFCGuidActivity.class); startActivity(intent); overridePendingTransition(R.anim.c_left_1_righttoleft, R.anim.c_left_2_lefttoright); } }); } @SuppressLint("NewApi") public void initNFC() { manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE); adapter = manager.getDefaultAdapter(); if (adapter != null) { if (adapter.isEnabled()) { tvNfc.setVisibility(View.GONE); } else { tvNfc.setVisibility(View.VISIBLE); } } else { tvNfc.setVisibility(View.VISIBLE); } } @Override protected void onResume() { super.onResume(); System.out.println("onResume"); if (adapter != null) { mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndefDetected = new IntentFilter( NfcAdapter.ACTION_NDEF_DISCOVERED); IntentFilter ndefDetected2 = new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED); IntentFilter ndefDetected3 = new IntentFilter( NfcAdapter.ACTION_TAG_DISCOVERED); try { ndefDetected.addDataType("*/*"); // } catch (MalformedMimeTypeException e) { throw new RuntimeException("fail", e); } techListsArray = new String[][] { new String[] { NfcA.class.getName(), NfcV.class.getName(), Ndef.class.getName(), NdefFormatable.class.getName(), MifareClassic.class.getName(), MifareUltralight.class.getName(), IsoDep.class.getName(), NfcB.class.getName(), NfcF.class.getName() } }; mWriteTagFilters = new IntentFilter[] { ndefDetected, ndefDetected2, ndefDetected3 }; adapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, techListsArray); Intent intent = this.getIntent(); resolveIntent(intent); // 這兩行代碼必定要寫 } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); System.out.println("onNewIntent"); resolveIntent(intent); } private void resolveIntent(Intent intent) { if (adapter != null) { NFCData nd = NFCUtil.getNFCIntentData(intent); if (nd != null) { String uid = nd.getUid(); if (uid != null && !"".equals(uid)) { intent = new Intent(NFCActivity.this, ResultActivity.class); intent.putExtra("nfcData", (Serializable) nd); startActivity(intent); overridePendingTransition(R.anim.c_left_1_righttoleft, R.anim.c_left_2_lefttoright); } } } } @Override protected void onPause() { super.onPause(); if (adapter != null) { adapter.disableForegroundDispatch(this); } } public void initTitile() { TextView tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.scan_nfc_title); ImageView iv_left = (ImageView) findViewById(R.id.iv_left); iv_left.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); overridePendingTransition(R.anim.c_right_1_lefttoright, R.anim.c_right_2_righttoleft); } }); ImageView iv_right = (ImageView) findViewById(R.id.iv_right); iv_right.setVisibility(View.INVISIBLE); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { this.finish(); overridePendingTransition(R.anim.c_right_1_lefttoright, R.anim.c_right_2_righttoleft); } return super.onKeyDown(keyCode, event); } }
下面是activity_nfc的佈局文件工具
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <include layout="@layout/title" /> <LinearLayout android:id="@+id/no_info_frag" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/noRecord" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center" android:layout_marginTop="127dp" android:src="@drawable/nfc_bitmap" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:text="@string/NFCText" android:textColor="@color/golden" android:layout_gravity="center" android:gravity="center" android:textSize="15sp" /> <TextView android:id="@+id/tv_nfc" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:text="@string/noNFCText" android:textColor="@color/red" android:layout_gravity="center" android:gravity="center" android:textSize="15sp" /> <TextView android:id="@+id/tv_open_nfc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="@string/openNFCText" android:textColor="#004190" android:layout_gravity="center" android:textSize="18sp" /> </LinearLayout> </LinearLayout>
使用一個ResultActivity來顯示NFC讀取到電子標籤的結果,用一個TextView 顯示就是了, 你們都懂的
佈局
package com.iotdc.android.app.nfc.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.iotdc.android.app.config.SystemConfig; import com.iotdc.android.app.scanner.R; public class NFCResultActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc_result); initTitleBar(); TextView tvRead = (TextView) findViewById(R.id.tv_nfc_read); Intent data = this.getIntent(); String uid = data.getStringExtra("nfcResult"); String msg = data.getStringExtra("msg"); SystemConfig.error(msg, this); tvRead.setText(uid); } private void initTitleBar(){ TextView tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.scan_nfc_title_result); ImageView iv_left = (ImageView) findViewById(R.id.iv_left); iv_left.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); overridePendingTransition(R.anim.c_right_1_lefttoright, R.anim.c_right_2_righttoleft); } }); ImageView iv_right = (ImageView) findViewById(R.id.iv_right); iv_right.setVisibility(View.INVISIBLE); } }
其中NFC讀取數據的方法我寫在了一個工具類中,叫NFCUtilui
package com.iotdc.android.app.utils; import java.io.Serializable; import android.annotation.SuppressLint; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.Tag; import com.iotdc.android.app.nfc.TagBlockStream; public class NFCUtil { @SuppressLint("NewApi") public static NFCData getNFCIntentData(Intent intent) { NFCData nd = new NFCData(); String uid = ""; String data = ""; String action = intent.getAction(); // 判斷nfc的類型,一共有三種 if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); TagBlockStream bs = TagBlockStream.getInstance(tagFromIntent); byte[] blockContent = null; // HonestTag hTag = null; uid = HexUtility.byteArrayToString(tagFromIntent.getId()); if (bs != null) { try { bs.connect(); blockContent = bs.readBlock(0); } catch (Exception e) { e.printStackTrace(); } finally { try { bs.close(); } catch (Exception e) { e.printStackTrace(); } } } } nd.setUid(uid); // 03190B0000014BE0 return nd; } public static class NFCData implements Serializable { /** * 標籤UID 值 */ private String uid; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } } }
到上面的話,邏輯代碼就已經完成了, 注意, 沒有完, NFC 必定要手機支持,而且要在Manifest.xml文件中進行權限配置this
<uses-permission android:name="android.permission.NFC" />
還要在對activity 進行過濾
spa
<activity android:name="com.iotdc.android.app.nfc.activity.NFCActivity" android:screenOrientation="portrait" > <!-- 這 一句必定是要的--> <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> </intent-filter> </activity>
到這裏, 全部的工做就都完成了, 對NFC 我也不是太瞭解,只是在工做中用到了, 目前在公司的話, 尚未接觸過手機與手機之間的通訊, 但願大神可以指導,共同進步code