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();
}
} }
NFC(7)向NFC硬件写入数据的两个示例(nfc硬件启动android应用,nfc硬件打开uri)的更多相关文章
- Android之NFC
来源:http://blog.csdn.net/bear_huangzhen/article/details/46333421 NFC简介: Near Field Communication 近场通信 ...
- 转载-python学习笔记之输入输出功能读取和写入数据
读取.写入和 Python 在 “探索 Python” 系列以前的文章中,学习了基本的 Python 数据类型和一些容器数据类型,例如tuple.string 和 list.其他文章讨论了 Pytho ...
- NFC(6)NFC编程的几个重要类,NFC硬件启动android应用原理
用于NFC编程的几个重要类 Tag NFC 标签 NfcAdapter Nfc 的适配类 NdefMessage 描述NDEF格式的信息 NdefRecord 描述NDEF信息的一个信息段,类似tab ...
- Android训练课程(Android Training) - NFC基础
NFC 基础 本文档介绍了在Android上的基本的NFC任务.它说明了如何发送和接收的NDEF消息(NDEF messages)的形式的表单里包含的NFC数据(NFC data),并介绍Androi ...
- Android下NFC的简单使用
现在很多手机已经配备了NFC(Near Field Communication 近场通信)的功能,我就为此专门研究过,可以到本文末尾下载源代码. Android官方资料:http://develope ...
- 关于android的nfc问题
最近在研究android的nfc问题 首先再网上有很多关于android nfc 读写的问题,但是大多数都是关于Mifare Classic类型卡的读写,我百试不得骑解,于是自己写了一些程序供大家参考 ...
- 5.Android之NFC介绍
NFC简介: Near Field Communication 近场通信,是一种数据传输技术. 与wifi.蓝牙.红外线等数据传输技术的一个主要差异就是有效距离一般不能超过4cm. NFC支持3种工作 ...
- 02使用java脚本向Pxc集群写入数据
使用java脚本向Pxc集群写入数据 批量写入pxc集群程序 导入mysql驱动包 # 批量插入数据的java脚本 package pxc_demo; import java.sql.Connecti ...
- MSSQL批量写入数据方案
近来有一个项目Feature需要有批量写入数据的场景,正巧整理资料发现自己以前也类似实现的项目,在重构的同时把相关资料做了一个简单的梳理,方便大家参考. 循环写入(简单粗暴,毕业设计就这样干的)(不推 ...
随机推荐
- Android TextUtil
Android中计算textView长度问题 今天有一个需求,需要TextView显示两行的信息,但是右下角区域需要空出来,要来显示一张小图片,要实现的效果如图所示. 这里遇到的问题是计算TextVi ...
- jQueryr .on方法解析
.On() 其实.bind(), .live(), .delegate()都是通过.on()来实现的,.unbind(), .die(), .undelegate(),也是一样的都是通过.off()来 ...
- vhost设定
vhost设定 http.conf <Directory /> AllowOverride none #Require all denied </Directory> ...
- angularjs--$watch、$watchGroup、$watchCollection含义
angularjs的$watch.$watchGroup.$watchCollection使用方式 如果想在controller里面随时监听一个值的变化那就用$watch <p> ...
- 【python】开始python之旅
上午开始抽空学习python,具体内容如下: (1)安装了python 2.7 (2)安装了notepad ++,安装它之前,在notepad++和Sublime Text之间纠结了一下,baidu了 ...
- epoll_create, epoll_ctl和epoll_wait
参考代码 #include <iostream> #include <sys/socket.h> #include <sys/epoll.h> #include & ...
- WPF中禁止WebBrowser控件打开新窗口
一.针对纯WPF的WebBrowser控件: <summary> Suppress Script Errors In WPF WebBrowser </summary> pub ...
- Google code: Why ‘Everything up-to-date’ when pushing (git)
原文链接:http://blog.rexzhao.com/2011/11/28/google-code-git-everything-up-to-date-when-push.html 第一次在Goo ...
- ENVI/IDL中.sav和.pro文件用法的不同
软件envi5.0 sp3 .sav是IDL binaryfile。 安装方法:把ENVIProgramGenerator.sav文件拷贝到…\Exelis\ENVI50\extensions\文件夹 ...
- 读书笔记汇总 --- 用Python写网络爬虫
本系列记录并分享:学习利用Python写网络爬虫的过程. 书目信息 Link 书名: 用Python写网络爬虫 作者: [澳]理查德 劳森(Richard Lawson) 原版名称: web scra ...