向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();
}
} }

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

  1. Android之NFC

    来源:http://blog.csdn.net/bear_huangzhen/article/details/46333421 NFC简介: Near Field Communication 近场通信 ...

  2. 转载-python学习笔记之输入输出功能读取和写入数据

    读取.写入和 Python 在 “探索 Python” 系列以前的文章中,学习了基本的 Python 数据类型和一些容器数据类型,例如tuple.string 和 list.其他文章讨论了 Pytho ...

  3. NFC(6)NFC编程的几个重要类,NFC硬件启动android应用原理

    用于NFC编程的几个重要类 Tag NFC 标签 NfcAdapter Nfc 的适配类 NdefMessage 描述NDEF格式的信息 NdefRecord 描述NDEF信息的一个信息段,类似tab ...

  4. Android训练课程(Android Training) - NFC基础

    NFC 基础 本文档介绍了在Android上的基本的NFC任务.它说明了如何发送和接收的NDEF消息(NDEF messages)的形式的表单里包含的NFC数据(NFC data),并介绍Androi ...

  5. Android下NFC的简单使用

    现在很多手机已经配备了NFC(Near Field Communication 近场通信)的功能,我就为此专门研究过,可以到本文末尾下载源代码. Android官方资料:http://develope ...

  6. 关于android的nfc问题

    最近在研究android的nfc问题 首先再网上有很多关于android nfc 读写的问题,但是大多数都是关于Mifare Classic类型卡的读写,我百试不得骑解,于是自己写了一些程序供大家参考 ...

  7. 5.Android之NFC介绍

    NFC简介: Near Field Communication 近场通信,是一种数据传输技术. 与wifi.蓝牙.红外线等数据传输技术的一个主要差异就是有效距离一般不能超过4cm. NFC支持3种工作 ...

  8. 02使用java脚本向Pxc集群写入数据

    使用java脚本向Pxc集群写入数据 批量写入pxc集群程序 导入mysql驱动包 # 批量插入数据的java脚本 package pxc_demo; import java.sql.Connecti ...

  9. MSSQL批量写入数据方案

    近来有一个项目Feature需要有批量写入数据的场景,正巧整理资料发现自己以前也类似实现的项目,在重构的同时把相关资料做了一个简单的梳理,方便大家参考. 循环写入(简单粗暴,毕业设计就这样干的)(不推 ...

随机推荐

  1. bootstrap-validator使用

    bootstrap-validator是一款与bootstrap相结合的表单前端验证模块,官方网址:http://1000hz.github.io/bootstrap-validator/ 下面内容大 ...

  2. DataGridView显示时间格式

    默认显示时间不显示秒yyyy-MM-dd HH:mm dataGridView.Columns["日期时间字段"].DefaultCellStyle.Format = " ...

  3. PHP学习之环境搭建

    计算机环境 win7  64位 搭建  apache-httpd-2.2-win64  +  php-5.3.6-Win32-VC9-x64  +MySQL_5.5.13_winx64开发环境 参考: ...

  4. pdo 连接数据库 报错 could not find driver 解决方法

    在windows 下,调试一个PHP程序时,报了这个错误, could not find driver 原来我的这个程序中用到了PDO对象, 连接mysql 5.  在PHP的默认设置中,只打开了ph ...

  5. 考研路之C语言

    今天在学习C的时候,又学到了一些新的内容,所以赶紧记录下来. case 1: #include <stdio.h> union exa{ struct{ int a; int b; }ou ...

  6. 文件大小的友好输出及其 Python 实现

    在数据库中存储时,使用 Bytes 更精确,可扩展性和灵活性都很高. 输出时,需要做一些适配. 1. 注意事项与测试代码 需要考虑 sizeInBytes 为 None 的场景. 除以 1024.0 ...

  7. 1. Linux驱动开发之开篇--Makefile

    基本Makefile假设现在有3个文件,file2.h是函数声明,file2.c是函数定义,文件file1.c调用file2.c中的函数.则Makefile文件的编写如下: helloworld:fi ...

  8. HashMap加入数据后,会自动根据首字母排序

    1.Map<String, ArrayList<XX>> entityHashMap = new HashMap<>(); 然后增加一些数据,会发现根据String ...

  9. Android 的自定义Spinner组件实现方式

    一.Android的API方式默认实现的方式 1.layout下编辑main_activity.xml <RelativeLayout xmlns:android="http://sc ...

  10. 约束的DEFERRABLE, NOT DEFERRABLE, INITIALLY IMMEDIATE 和 INITIALLY DEFERRED

    [ CONSTRAINT constraint_name ] { NOT NULL |   NULL |   CHECK ( expression ) [ NO INHERIT ] |   DEFAU ...