• 12、NFC技术:读写NFC标签中的Uri数据


    功能实现,如下代码所示:

    读写NFC标签的Uri 主Activity

     

      1 import cn.read.write.uri.library.UriRecord;
      2 import android.app.Activity;
      3 import android.content.Intent;
      4 import android.nfc.NdefMessage;
      5 import android.nfc.NdefRecord;
      6 import android.nfc.NfcAdapter;
      7 import android.nfc.Tag;
      8 import android.nfc.tech.Ndef;
      9 import android.os.Bundle;
     10 import android.view.View;
     11 import android.widget.TextView;
     12 import android.widget.Toast;
     13 
     14 /**
     15  * 读写NFC标签的Uri
     16  * @author dr
     17  *
     18  */
     19 public class ReadWriteUriMainActivity extends Activity {
     20     private TextView mSelectUri;
     21     private String mUri;
     22 
     23     @Override
     24     public void onCreate(Bundle savedInstanceState) {
     25         super.onCreate(savedInstanceState);
     26         setContentView(R.layout.activity_read_write_uri_main);
     27         mSelectUri = (TextView) findViewById(R.id.textview_uri);
     28     }
     29 
     30     public void onClick_SelectUri(View view) {
     31         Intent intent = new Intent(this, UriListActivity.class);
     32         startActivityForResult(intent, 1);
     33     }
     34 
     35     @Override
     36     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     37         if (requestCode == 1 && resultCode == 1) {
     38             mUri = data.getStringExtra("uri");
     39             mSelectUri.setText(mUri);
     40         }
     41     }
     42 
     43     public void onNewIntent(Intent intent) {
     44         if (mUri == null) {
     45             Intent myIntent = new Intent(this, ShowNFCTagContentActivity.class);
     46             myIntent.putExtras(intent);
     47             myIntent.setAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
     48             startActivity(myIntent);
     49         } else {  // write nfc
     50             Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
     51             NdefMessage ndefMessage = new NdefMessage(
     52                     new NdefRecord[] { createUriRecord(mUri) });
     53             if (writeTag(ndefMessage, tag)) {
     54                 mUri = null;
     55                 mSelectUri.setText("");
     56             }
     57         }
     58     }
     59 
     60     public NdefRecord createUriRecord(String uriStr) {
     61         byte prefix = 0;
     62         for (Byte b : UriRecord.URI_PREFIX_MAP.keySet()) {
     63             String prefixStr = UriRecord.URI_PREFIX_MAP.get(b).toLowerCase();
     64             if ("".equals(prefixStr))
     65                 continue;
     66             if (uriStr.toLowerCase().startsWith(prefixStr)) {
     67                 prefix = b;
     68                 uriStr = uriStr.substring(prefixStr.length());
     69                 break;
     70             }
     71         }
     72         byte[] data = new byte[1 + uriStr.length()];
     73         data[0] = prefix;
     74         System.arraycopy(uriStr.getBytes(), 0, data, 1, uriStr.length());
     75 
     76         NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
     77                 NdefRecord.RTD_URI, new byte[0], data);
     78         return record;
     79     }
     80 
     81     boolean writeTag(NdefMessage message, Tag tag) {
     82         int size = message.toByteArray().length;
     83         try {
     84             Ndef ndef = Ndef.get(tag);
     85             if (ndef != null) {
     86                 ndef.connect();
     87                 if (!ndef.isWritable()) {
     88                     return false;
     89                 }
     90                 if (ndef.getMaxSize() < size) {
     91                     return false;
     92                 }
     93                 ndef.writeNdefMessage(message);
     94                 Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
     95                 return true;
     96             }
     97         } catch (Exception e) {
     98             // TODO: handle exception
     99         }
    100         return false;
    101     }
    102 }

     

     

    读写NFC标签的Uri 主xml

     

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     android:orientation="vertical" >
     6 
     7     <Button
     8         android:layout_width="match_parent"
     9         android:layout_height="wrap_content"
    10         android:onClick="onClick_SelectUri"
    11         android:text="选择Uri" />
    12 
    13     <TextView
    14         android:id="@+id/textview_uri"
    15         android:layout_width="match_parent"
    16         android:layout_height="wrap_content"
    17         android:textSize="16sp" />
    18 
    19     <TextView
    20         android:layout_width="match_parent"
    21         android:layout_height="wrap_content"
    22         android:layout_marginTop="30dp"
    23         android:text="请将NFC标签靠近手机背面读取或写入Uri"
    24         android:textColor="#F00"
    25         android:textSize="16sp" />
    26 
    27     <ImageView
    28         android:layout_width="match_parent"
    29         android:layout_height="match_parent"
    30         android:src="@drawable/read_nfc_tag" />
    31 
    32 </LinearLayout>

     

     

    显示URI列表Activity

     1 import android.app.ListActivity;
     2 import android.content.Intent;
     3 import android.os.Bundle;
     4 import android.view.View;
     5 import android.widget.AdapterView;
     6 import android.widget.AdapterView.OnItemClickListener;
     7 import android.widget.ArrayAdapter;
     8 
     9 /**
    10  * 显示URI列表
    11  * @author dr
    12  *
    13  */
    14 public class UriListActivity extends ListActivity implements
    15         OnItemClickListener {
    16     private String uris[] = new String[] { "http://www.google.com",
    17             "http://www.apple.com", "http://developer.apple.com",
    18             "http://www.126.com", "ftp://192.168.17.160",
    19             "https://192.168.17.120", "smb://192.168.17.100" };
    20 
    21     @Override
    22     public void onCreate(Bundle savedInstanceState) {
    23         super.onCreate(savedInstanceState);
    24         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
    25                 android.R.layout.simple_list_item_1, android.R.id.text1, uris);
    26         setListAdapter(arrayAdapter);
    27         getListView().setOnItemClickListener(this);
    28     }
    29 
    30     @Override
    31     public void onItemClick(AdapterView<?> parent, View view, int position,
    32             long id) {
    33         Intent intent = new Intent();
    34         intent.putExtra("uri", uris[position]);
    35         setResult(1, intent);
    36         finish();
    37     }
    38 
    39 }

    显示NFC标签内容Activity

     1 import android.app.Activity;
     2 import android.nfc.NdefMessage;
     3 import android.nfc.NdefRecord;
     4 import android.nfc.NfcAdapter;
     5 import android.nfc.Tag;
     6 import android.nfc.tech.Ndef;
     7 import android.os.Bundle;
     8 import android.os.Parcelable;
     9 import android.widget.TextView;
    10 import cn.read.write.uri.library.UriRecord;
    11 
    12 /**
    13  * 显示NFC标签内容
    14  * @author dr
    15  *
    16  */
    17 public class ShowNFCTagContentActivity extends Activity {
    18     private TextView mTagContent;
    19     private Tag mDetectedTag;
    20     private String mTagText;
    21 
    22     @Override
    23     public void onCreate(Bundle savedInstanceState) {
    24         super.onCreate(savedInstanceState);
    25         setContentView(R.layout.activity_show_nfctag_content);
    26         mTagContent = (TextView) findViewById(R.id.textview_tag_content);
    27         mDetectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
    28         Ndef ndef = Ndef.get(mDetectedTag);
    29         mTagText = ndef.getType() + "
     max size:" + ndef.getMaxSize()
    30                 + " bytes
    
    ";
    31 
    32         readNFCTag();
    33 
    34         mTagContent.setText(mTagText);
    35     }
    36 
    37     private void readNFCTag() {
    38         if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
    39             Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(
    40                     NfcAdapter.EXTRA_NDEF_MESSAGES);
    41 
    42             NdefMessage ndefMessage = null;
    43 
    44             int contentSize = 0;
    45             if (rawMsgs != null) {
    46                 if (rawMsgs.length > 0) {
    47                     ndefMessage = (NdefMessage) rawMsgs[0];
    48                     contentSize = ndefMessage.toByteArray().length;
    49                 } else {
    50                     return;
    51                 }
    52             }
    53             try {
    54                 NdefRecord ndefRecord = ndefMessage.getRecords()[0];
    55                 UriRecord uriRecord = UriRecord.parse(ndefRecord);
    56                 mTagText += uriRecord.getUri().toString() + "
    
    Uri
    "
    57                         + contentSize + " bytes";
    58             } catch (Exception e) {
    59                 // TODO: handle exception
    60             }
    61         }
    62     }
    63 
    64 }

    显示NFC标签内容xml

     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     android:layout_width="match_parent"
     3     android:layout_height="match_parent"
     4     android:orientation="vertical" >
     5 
     6     <TextView
     7         android:id="@+id/textview_tag_content"
     8         android:layout_width="match_parent"
     9         android:layout_height="wrap_content"
    10         android:layout_margin="6dp"
    11         android:textSize="16sp" />
    12 
    13 </LinearLayout>

    AndroidManifest.xml

     1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     2     package="cn.eoe.read.write.uri"
     3     android:versionCode="1"
     4     android:versionName="1.0" >
     5 
     6     <uses-sdk
     7         android:minSdkVersion="15"
     8         android:targetSdkVersion="15" />
     9 
    10     <uses-permission android:name="android.permission.NFC" />
    11 
    12     <application
    13         android:icon="@drawable/ic_launcher"
    14         android:label="@string/app_name"
    15         android:theme="@style/AppTheme" >
    16         <activity
    17             android:name=".ReadWriteUriMainActivity"
    18             android:label="读写NFC标签的Uri"
    19             android:launchMode="singleTask" >
    20             <intent-filter>
    21                 <action android:name="android.intent.action.MAIN" />
    22 
    23                 <category android:name="android.intent.category.LAUNCHER" />
    24             </intent-filter>
    25             <intent-filter>
    26                 <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    27 
    28                 <category android:name="android.intent.category.DEFAULT" />
    29 
    30                 <data android:scheme="http" />
    31                 <data android:scheme="https" />
    32                 <data android:scheme="ftp" />
    33             </intent-filter>
    34             <intent-filter>
    35                 <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    36 
    37                 <category android:name="android.intent.category.DEFAULT" />
    38                 <data android:mimeType="text/plain" />
    39             </intent-filter>
    40         </activity>
    41         <activity
    42             android:name="cn.eoe.read.write.uri.ShowNFCTagContentActivity"
    43             android:label="显示NFC标签内容" />
    44         <activity
    45             android:name="cn.eoe.read.write.uri.UriListActivity"
    46             android:label="选择Uri" />
    47     </application>
    48 
    49 </manifest>

    DEMO下载地址:http://download.csdn.net/detail/androidsj/7680247

     

     

  • 相关阅读:
    Mysql多表关系
    Linux权限
    Linux安装python环境脚本
    ZJNU 2136
    ZJNU 2135
    ZJNU 2133
    ZJNU 1699
    ZJNU 1542
    ZJNU 1538
    ZJNU 1535
  • 原文地址:https://www.cnblogs.com/androidsj/p/3856435.html
Copyright © 2020-2023  润新知