用于描述NDEF格式数据的两个重要的类

NdefMessage:描述NDEF格式的信息
NdefRecord:描述NDEF信息的一个信息段 

NdefMessage和NdefRecord是Android NFC技术的核心类,无论读写NDEF格式的NFC标签,还是通过Android Beam技术传递Ndef格式的数据,都需要这两个类。

 
向NFC标签写入数据的步骤
获取Tag对象

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

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

Ndef ndef = Ndef.get(tag);

写入数据

ndef.writeNdefMessage(ndefMessage);

示例:自动启动Android应用程序
      
 最终效果:写入后,关闭程序,回到主页面,然后拿NFC标签靠近手机后盖上部,程序回自动运行。  实现代码如下所示。
 import java.util.ArrayList;
import java.util.List; import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter; /**
* LIST列表,显示所有的包。
* @author dr
*/
public class InstalledApplicationListActivity extends ListActivity implements
OnItemClickListener { private List<String> mPackages = new ArrayList<String>(); @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // 获取所有程序包名称,并且循环显示出来。
PackageManager packageManager = getPackageManager();
List<PackageInfo> packageInfos = packageManager
.getInstalledPackages(PackageManager.GET_ACTIVITIES);
for (PackageInfo packageInfo : packageInfos) {
mPackages.add(packageInfo.applicationInfo.loadLabel(packageManager)
+ "\n" + packageInfo.packageName);
} ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
mPackages);
setListAdapter(arrayAdapter);
// 列表项,单击事件。
getListView().setOnItemClickListener(this);
} @Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent();
// 把选中的包名传过去
intent.putExtra("package_name", mPackages.get(position));
setResult(1, intent);
finish(); } }
 mport 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;
private PendingIntent mPendingIntent; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_run_application); mSelectAutoRunApplication = (Button) findViewById(R.id.button_select_auto_run_application); mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
// 一旦截获NFC消息后,通过PendingIntent来调用
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()), 0); } public void onResume() { // 当窗口获得焦点时
super.onResume(); if (mNfcAdapter != null)
// (一旦截获NFC消息)优先级,优于所有的(处理NFC标签)窗口
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
null);
} public void onPause() { //
super.onPause(); if (mNfcAdapter != null)
// 取消,把窗口恢复到正常状态。
mNfcAdapter.disableForegroundDispatch(this);
} public void onClick_SelectAutoRunApplication(View view) {
Intent intent = new Intent(this, InstalledApplicationListActivity.class);
startActivityForResult(intent, 0);
} /**
* 因为此Activity配置配件中设置成singleTop(第2次运行onCreate将不会创建新的窗口实例),
* 不能在onCreate中获取Intent传过来的TAG数据。 但是,会调用此方法,onNewIntent也是Activity里面的方法。
*/
public void onNewIntent(Intent intent) {
if (mPackageName == null)
return;
// 获得Tag。
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// 写入标签。
writeNFCTag(detectedTag);
} public void writeNFCTag(Tag tag) {
if (tag == null) {
return;
}
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { NdefRecord
.createApplicationRecord(mPackageName) });
int size = ndefMessage.toByteArray().length;
try {
// 判断NFC标签的数据类型。
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect(); // 建立连接 if (!ndef.isWritable()) { // 判断NFC标签是否可写。
return;
}
if (ndef.getMaxSize() < size) { // 最大尺寸<写入尺寸。
return;
}
// 写入数据。
ndef.writeNdefMessage(ndefMessage);
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
} } catch (Exception e) {
// TODO: handle exception
}
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
mSelectAutoRunApplication.setText(data.getExtras().getString(
"package_name"));
String temp = mSelectAutoRunApplication.getText().toString();
mPackageName = temp.substring(temp.indexOf("\n") + 1); } } }
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/button_select_auto_run_application"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick_SelectAutoRunApplication"
android:text="选择已安装的应用程序" /> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="请将NFC标签或贴纸靠近手机背面"
android:textSize="16sp" /> <ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:src="@drawable/read_nfc_tag" /> </LinearLayout>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.eoe.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>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

7、NFC技术:让Android自动运行程序的更多相关文章

  1. 【转】]Android实现开机自动运行程序

    有些时候,应用需要在开机时就自动运行,例如某个自动从网上更新内容的后台service.怎样实现开机自动运行的应用?在撰写本文时,联想到高焕堂先生以“Don't call me, I'll call y ...

  2. Android实现开机自动运行程序

    有些时候,应用需要在开机时就自动运行,例如某个自动从网上更新内容的后台service.怎样实现开机自动运行的应用?在撰写本文时,联想到高焕堂先生以“Don't call me, I'll call y ...

  3. 如何在Linux实现自动运行程序

    1.开机启动时 Linux加载后, 它将初始化硬件和设备驱动, 然后运行第一个进程init. init根据配置文件继续引导过程,启动其它进程.通常情况下,修改放置在 /etc/rc或 /etc/rc. ...

  4. 如何在LINUX中开机、登陆、退出、定时、定期自动运行程序

    1.开机启动时自动运行程序 Linux加载后, 它将初始化硬件和设备驱动, 然后运行第一个进程init.init根据配置文件继续引导过程,启动其它进程.通常情况下,修改放置在 /etc/rc或 /et ...

  5. 第一次通过AVD Manager创建了一个虚拟设备,但是在Android Studio运行程序时却无设备可选

    第一次通过AVD Manager创建了一个虚拟设备,但是在Android Studio运行程序时却无设备可选 原因是adb.exe未运行起来 至于adb.exe未正常运行起来的原因多半是5037端口被 ...

  6. CentOS开机自动运行程序的脚本

    有些时候我们需要在服务器里设置一个脚本,让他一开机就自己启动.方法如下: cd /etc/init.dvi youshell.sh   #将youshell.sh修改为你自己的脚本名编写自己的脚本后保 ...

  7. /etc/rc.local 与 /etc/init.d Linux 开机自动运行程序

    1. /etc/rc.local 这是使用者自订开机启动程序,把需要开机自动运行的程序写在这个脚本里 --------引用---------------------- 在完成 run level 3 ...

  8. Android Studio运行程序,检测不到(夜神、Genymotion)模拟器

    用了统一给的android studio,运行程序,检测不到模拟器(夜神). 又新建了一个系统的模拟器,运行,提示ANDROID_SDK_ROOT is undefined 在环境变量中配置之后,夜神 ...

  9. [VC]VC实现开机自动运行程序

    有时候,我们需要在计算机启动的时候就启动某些程序,不要人干预.这里,提供一种让程序开机自动运行的方法.见下面代码: BOOL CXXX::SetAutoRun(CString strPath) { C ...

随机推荐

  1. iOS 开发--添加工程

    文/Bison(简书作者)原文链接:http://www.jianshu.com/p/dd71e15df5d0著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 第一部分,配置项目 在此只 ...

  2. React属性的3种设置方式

    一. 不推荐用setProps,因为以React的设计思想相悖,推荐以父组件向子组件传递属性的方式 二.3种用法的代码 1.键值对 <!DOCTYPE html> <html lan ...

  3. Ajax实例-购物车

    一.概述 1.当添加或删除商品时,购物车会立即更新数据 2.思路: (1)建立商品类Item.java,存有商品属性name,prince,code(商品编码)等 (2)建立商品目录类Catalog. ...

  4. 把Message转换成String

    把Message转换成String注意,这里欠缺CM消息和CN消息,因为它们不是系统消息,不经过Dispatch API转发,但是可以把它们写在WndProc里,这样SendMessage送来的消息也 ...

  5. 对所有CPU寄存器的简述(16位CPU14个,32位CPU16个)

    32位CPU所含有的寄存器有:4个数据寄存器(EAX.EBX.ECX和EDX)2个变址和指针寄存器(ESI和EDI)2个指针寄存器(ESP和EBP)6个段寄存器(ES.CS.SS.DS.FS和GS)1 ...

  6. Intellij编译时报“java: System Java Compiler was not found in classpath” 解决办法

    Intellij编译时报“java: System Java Compiler was not found in classpath” 解决方法: Project Settings > Comp ...

  7. POJ1088滑雪

    Description Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激.可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你.Michael想知道 ...

  8. EasyUi datagrid 表格分页例子

    1.首先引入 easyui的 css 和 js 文件 2.前台 需要写的js //源数据 function Async(action,args,callback){  $.ajax({  url: a ...

  9. Java实体书写规范

    ** * 用户角色表 */ public class BaseUserRole implements Serializable { private static final long serialVe ...

  10. JWFD开源项目官方网站预览

    自己做的...感觉还比较正规哈....JWFD开源项目还是需要一个官方网站的...