乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Android中NFC功能流程圖解析及代碼演示

       Colin收藏 2012-05-24
      在Android4.0推出的時候,一個非常引人注目的功能就是NFC(Near Field Communication).

      Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.

      翻譯:
      近場通訊(NFC)是一系列短距離無線技術,一般需要4cm或者更短去初始化連接。近場通訊(NFC)允許你在NFC tag和Android設備或者兩個Android設備間共享小負載數(shù)據(jù)。

      典型的應用為刷卡應用,如刷信用卡,公交車卡,吃飯的飯卡之類。騰訊2011年1月份文章“Android首款NFC近場通信應用推出”,說明了基于Android的NFC應用目前已經(jīng)有了,得益于日本在手機刷卡的應用氛圍。據(jù)2011年7月網(wǎng)易文章“PayPal推出Android系統(tǒng)NFC移動支付服務”報道,PayPal已經(jīng)做了嘗試了,相信這股風很快要刮到中國。

      下面我們從技術的層面來分析一下這個技術。



      官方的圖片示例為:



      這是NFC的開發(fā)流程,參考文章 “【NFC在android中的應用API】”。
      相關的類代碼有:NfcAdapter,NdefMessage, NdefRecord,ACTION_TAG_DISCOVERED.
      在功能層面上,涉及到了NFC的讀寫功能。下面我們分別來做總結(jié)。
      在代碼層上面:

      使用的時候,需要在AndroidManifest.xml里面加一些權限以及屬性。

      代碼片段,雙擊復制
      01
      02
      03
      <uses-permission android:name="android.permission.NFC"/>
      <uses-feature android:name="android.hardware.nfc" android:required="true"/>
      <uses-sdk android:minSdkVersion="10"/>



      這里注意,在Android Version 9的時候僅僅支持了ACTION_TAG_DISCOVERED,對于其他的需要10以上。
      在上面的基礎上,還需要增加intent-filter的支持。

      代碼片段,雙擊復制
      01
      02
      03
      04
      <intent-filter>
      <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
      <category android:name="android.intent.category.DEFAULT"/>
       <data android:mimeType="text/plain"/></intent-filter>


      獲取NfcAdapter的代碼為
      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      08
      09
      10
      11
      public static String getStatusNfcDevice () {
      NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter();
      if (nfcAdapter.isEnabled()) {
      String status = "enabled";
      return status;
      }
      else {
      String status = "disabled";
      return status;
      }
      }


      處理函數(shù)為

      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      08
      09
      10
      11
      12
      13
      public void onResume() {
      super.onResume();
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      if (rawMsgs != null) {
      msgs = new NdefMessage[rawMsgs.length];
      for (int i = 0; i < rawMsgs.length; i++) {
      msgs<i> = (NdefMessage) rawMsgs<i>;
      }
      }
      }
      //process the msgs array
      }</i></i>


      完整的一個操作代碼摘自Google Android NFC Guide代碼(略加注釋):

      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      08
      09
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      package com.example.android.beam;
       
      import android.app.Activity;
      import android.content.Intent;
      import android.nfc.NdefMessage;
      import android.nfc.NdefRecord;
      import android.nfc.NfcAdapter;
      import android.nfc.NfcAdapter.CreateNdefMessageCallback;
      import android.nfc.NfcEvent;
      import android.os.Bundle;
      import android.os.Parcelable;
      import android.widget.TextView;
      import android.widget.Toast;
      import java.nio.charset.Charset;
       
      //繼承并實現(xiàn)接口CreateNdefMessageCallback方法createNdefMessage
      public class Beam extends Activity implements CreateNdefMessageCallback {
      NfcAdapter mNfcAdapter;
      TextView textView;
       
      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      TextView textView = (TextView) findViewById(R.id.textView);
      // Check for available NFC Adapter
      //檢測是否有NFC適配器
      mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
      if (mNfcAdapter == null) {
      Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
      finish();
      return;
      }
      // Register callback
      //注冊回調(diào)函數(shù)
      mNfcAdapter.setNdefPushMessageCallback(this, this);
      }
       
      @Override
      public NdefMessage createNdefMessage(NfcEvent event) {
      String text = ("Beam me up, Android!\n\n" +
      "Beam Time: " + System.currentTimeMillis());
      //回調(diào)函數(shù),構(gòu)造NdefMessage格式
      NdefMessage msg = new NdefMessage(
      new NdefRecord[] { createMimeRecord(
      "application/com.example.android.beam", text.getBytes())
      /**
      * The Android Application Record (AAR) is commented out. When a device
      * receives a push with an AAR in it, the application specified in the AAR
      * is guaranteed to run. The AAR overrides the tag dispatch system.
      * You can add it back in to guarantee that this
      * activity starts when receiving a beamed message. For now, this code
      * uses the tag dispatch system.
      */
      //,NdefRecord.createApplicationRecord("com.example.android.beam")
      });
      return msg;
      }
       
      @Override
      public void onResume() {
      super.onResume();
      // Check to see that the Activity started due to an Android Beam
      //得到是否檢測到ACTION_NDEF_DISCOVERED觸發(fā)
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
      processIntent(getIntent());
      }
      }
       
      //重載Activity類方法處理當新Intent到來事件
      @Override
      public void onNewIntent(Intent intent) {
      // onResume gets called after this to handle the intent
      setIntent(intent);
      }
       
      /**
      * Parses the NDEF Message from the intent and prints to the TextView
      */
      //關鍵處理函數(shù),處理掃描到的NdefMessage
      void processIntent(Intent intent) {
      textView = (TextView) findViewById(R.id.textView);
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
      NfcAdapter.EXTRA_NDEF_MESSAGES);
      // only one message sent during the beam
      NdefMessage msg = (NdefMessage) rawMsgs[0];
      // record 0 contains the MIME type, record 1 is the AAR, if present
      textView.setText(new String(msg.getRecords()[0].getPayload()));
      }
       
      /**
      * Creates a custom MIME type encapsulated in an NDEF record
      */
      public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
      byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
      NdefRecord mimeRecord = new NdefRecord(
      NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
      return mimeRecord;
      }
      }



      上面代碼還需要在AndroidManifest.xml文件里面添加
      <intent-filter>
        < action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        < category android:name="android.intent.category.DEFAULT"/>
        < data android:mimeType="application/com.example.android.beam"/>
      < /intent-filter>

      在對NFC設備進行寫操作的時候,相關代碼:

      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      private void enableTagWriteMode() {
      mWriteMode = true;
      IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
      mWriteTagFilters = new IntentFilter[] { tagDetected };
      mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
      }


      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      08
      09
      10
      11
      12
      13
      14
      @Override
      protected void onNewIntent(Intent intent) {
      // Tag writing mode
      if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
      Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      if (NfcUtils.writeTag(NfcUtils.getPlaceidAsNdef(placeidToWrite), detectedTag)) {
      Toast.makeText(this, "Success: Wrote placeid to nfc tag", Toast.LENGTH_LONG)
      .show();
      NfcUtils.soundNotify(this);
      } else {
      Toast.makeText(this, "Write failed", Toast.LENGTH_LONG).show();
      }
      }
      }


      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      08
      09
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      /*
      * Writes an NdefMessage to a NFC tag
      */
      public static boolean writeTag(NdefMessage message, Tag tag) {
      int size = message.toByteArray().length;
      try {
      Ndef ndef = Ndef.get(tag);
      if (ndef != null) {
      ndef.connect();
      if (!ndef.isWritable()) {
      return false;
      }
      if (ndef.getMaxSize() < size) {
      return false;
      }
      ndef.writeNdefMessage(message);
      return true;
      } else {
      NdefFormatable format = NdefFormatable.get(tag);
      if (format != null) {
      try {
      format.connect();
      format.format(message);
      return true;
      } catch (IOException e) {
      return false;
      }
      } else {
      return false;
      }
      }
      } catch (Exception e) {
      return false;
      }
      }


      代碼片段,雙擊復制
      01
      02
      03
      04
      05
      06
      07
      <activity android:name=".CheckInActivity">
      <intent-filter>
      <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
      <data android:mimeType="application/vnd.facebook.places"/>
      <category android:name="android.intent.category.DEFAULT"/>
      </intent-filter>
      </activity>







        本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多