NFC(7)向NFC硬件写入数据的两个示例(nfc硬件启动android应用,nfc硬件打开uri)

时间:2023-03-09 17:13:17
NFC(7)向NFC硬件写入数据的两个示例(nfc硬件启动android应用,nfc硬件打开uri)

向NFC标签写入数据基本步骤

1,获取Tag对象

  Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

2,判断NFC标签的数据类型(通过Ndef.get方法)

  Ndef ndef = Ndef.get(tag);

3,NFC开始连接

  ndef.connect();

4,建NdefMessage数据,然后将它写入数据
  ndef.writeNdefMessage(ndefMessage);

示例1: nfc标签设备启动android应用

 import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class RunApplicationActivity extends Activity { private Button mSelectAutoRunApplication;
private String mPackageName; private NfcAdapter mNfcAdapter;//用来NFC通信
private PendingIntent mPendingIntent;//用来封装当前窗口 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_run_application); mSelectAutoRunApplication = (Button) findViewById(R.id.button_select_auto_run_application); mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, , new Intent(this,
getClass()), ); }
//从另一个aty中取出数据.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == )
{
mSelectAutoRunApplication.setText(data.getExtras().getString(
"package_name"));
String temp = mSelectAutoRunApplication.getText().toString();
mPackageName = temp.substring(temp.indexOf("\n") + ); } }
//由于在manifest.xml中指定当前aty主singleTop,所以startactivity时 onCreate只被调用一次.
//但是onNewIntent在startactivity会被调用
@Override
public void onNewIntent(Intent intent) {
if (mPackageName == null)
return; //第1步,取得NFC 标签
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); writeNFCTag(detectedTag);//自写的成员函数
} //第4种 过滤方法的开始函数,要比3种过滤方法优先级高
@Override
public void onResume() {
super.onResume();
//在Resume时让当前窗口优先处理nfc数据
if (mNfcAdapter != null){
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
null);
}
}
//第4种 过滤方法结束函数,要比3种过滤方法优先级高
@Override
public void onPause() {
super.onPause();
//在onPause时取消让当前窗口优先处理nfc数据
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
public void onClick_SelectAutoRunApplication(View view)
{
Intent intent = new Intent(this, InstalledApplicationListActivity.class);
startActivityForResult(intent, );
}
//向nfc标签写入数据的函数
public void writeNFCTag(Tag tag) {
if (tag == null) {
return;
}
try {
//第2步,判断NFC标签的数据类型(通过Ndef.get方法)
Ndef ndef = Ndef.get(tag); if(ndef != null )
{
//第3步,NFC开始连接
ndef.connect(); if(!ndef.isWritable())//标签是否可写.
{
return;
}
//第4步,准备数据
//一个NdefMessage 中可有多个NdefRecord,它们之间关系类似table与record
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { NdefRecord
.createApplicationRecord(mPackageName) });
int size = ndefMessage.toByteArray().length;
if(ndef.getMaxSize() < size)
{
return;
}
//第5步,把数据写入到nfc标签中.
ndef.writeNdefMessage(ndefMessage);
//第6步,写入成功提示
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
//有可能异常
e.printStackTrace();
}
}
}

manifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.e.run.application"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.NFC" /> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".RunApplicationActivity"
android:label="@string/title_activity_auto_run_application"
android:launchMode="singleTop"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".InstalledApplicationListActivity"
android:label="@string/title_activity_installed_application_list"
android:screenOrientation="portrait" /> </application> </manifest>

示例2: nfc标签设备打开一个uri

 import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.widget.Toast; public class AutoOpenUriActivity extends Activity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_open_uri);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, , new Intent(this,
getClass()), ); } @Override
public void onResume() {
super.onResume();
if (nfcAdapter != null)
nfcAdapter
.enableForegroundDispatch(this, pendingIntent, null, null);
} @Override
public void onNewIntent(Intent intent) {
//第1步,取得NFC 标签
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeNFCTag(detectedTag);
} @Override
public void onPause() {
super.onPause();
if (nfcAdapter != null)
nfcAdapter.disableForegroundDispatch(this); } public void writeNFCTag(Tag tag) {
if (tag == null) {
return;
}
Uri uri = Uri.parse("http://www.bing.com");
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { NdefRecord.createUri(uri) });
int size = ndefMessage.toByteArray().length;
try{
Ndef ndef = Ndef.get(tag); if (ndef != null){// 已经格式化
ndef.connect();
if (!ndef.isWritable()) {
return;
}
if (ndef.getMaxSize() < size) {
return;
}
ndef.writeNdefMessage(ndefMessage);
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
} else {// 标签未格式化
// 第1步,获取NdefFormatable
NdefFormatable format = NdefFormatable.get(tag);
if (format != null){// 可以格式化
// 第2步,连接
format.connect();
// 第3步,格式化同时把数据写入到标签中.
format.format(ndefMessage);
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
} else {// 不可格式化
Toast.makeText(this, "formating is failed",
Toast.LENGTH_LONG).show();
}
} } catch (Exception e) {
e.printStackTrace();
}
} }