Android Beam的基本理念

Android Beam的基本理念就是两部(只能是两部)NFC设备靠近时(一般是背靠背),通过触摸一部NFC设备的屏幕,将数据推向另外一部NFC设备。在传递数据的过程中,两部NFC设备不能离得太远,否则NFC连接将中断。

Android Beam API

Android SDK提供了如下两个用于传递消息的方法。

NfcAdapter.setNdefPushMessage
NfcAdapter.setNdefPushMessageCallback

public void setNdefPushMessage(NdefMessage message, Activity activity, Activity ... activities);

public void setNdefPushMessageCallback(CreateNdefMessageCallback callback, Activity activity, Activity ... activities);

public NdefMessage createNdefMessage(NfcEvent event)

Demo

          
 import java.nio.charset.Charset;
import java.util.Locale; 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.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast; /**
* 两部android手机,进行传入文本信息。
* @author dr
*
*/
public class AndroidBeamMainActivity extends Activity implements
CreateNdefMessageCallback, OnNdefPushCompleteCallback { private EditText mBeamText; private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_android_beam);
mBeamText = (EditText) findViewById(R.id.edittext_beam_text); mNfcAdapter = mNfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()), 0); mNfcAdapter.setNdefPushMessageCallback(this, this);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
} @Override /** 窗口处理完成 */
public void onNdefPushComplete(NfcEvent event) {
Log.d("message", "complete");
} @Override /** 如果另外一台手机,靠近当前这部手机 */
public NdefMessage createNdefMessage(NfcEvent event) {
String text = mBeamText.getText().toString().trim();
if ("".equals(text))
text = "默认文本";
/*
* "com.android.calculator2" 官方原生计算器包。
* 当另外一部手机靠近这部手机时,会启动计算器。
*
* NdefMessage ndefMessage = new NdefMessage( new NdefRecord[] {
* NdefRecord .createApplicationRecord("com.android.calculator2") });
*/
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { createTextRecord(text) }); return ndefMessage;
} @Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null)
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
null);
} @Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
} @Override
public void onNewIntent(Intent intent) {
// 用于显示接收手机的信息。如果接收手机没有打开,会默认调用系统的黑界面。
processIntent(intent);
} /** 根据文本创建 NdefRecord 这个对象 */
public NdefRecord createTextRecord(String text) {
byte[] langBytes = Locale.CHINA.getLanguage().getBytes(
Charset.forName("US-ASCII"));
Charset utfEncoding = Charset.forName("UTF-8");
byte[] textBytes = text.getBytes(utfEncoding);
int utfBit = 0;
char status = (char) (utfBit + langBytes.length);
byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte) status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
textBytes.length);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data); return record;
} void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0];
String text = TextRecord.parse(msg.getRecords()[0]).getText();
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
 import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import android.nfc.NdefRecord; public class TextRecord {
private final String mText; private TextRecord(String text) {
mText = text;
} public String getText() {
return mText;
} // 将纯文本内容从NdefRecord对象中解析出来
public static TextRecord parse(NdefRecord record) { if (record.getTnf() != NdefRecord.TNF_WELL_KNOWN)
return null;
if (!Arrays.equals(record.getType(), NdefRecord.RTD_TEXT))
return null; try {
byte[] payload = record.getPayload();
/*
* payload[0] contains the "Status Byte Encodings" field, per the
* NFC Forum "Text Record Type Definition" section 3.2.1.
*
* bit7 is the Text Encoding Field.
*
* if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
* The text is encoded in UTF16
*
* Bit_6 is reserved for future use and must be set to zero.
*
* Bits 5 to 0 are the length of the IANA language code.
*/
String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8"
: "UTF-16";
int languageCodeLength = payload[0] & 0x3f;
String languageCode = new String(payload, 1, languageCodeLength,
"US-ASCII");
String text = new String(payload, languageCodeLength + 1,
payload.length - languageCodeLength - 1, textEncoding);
return new TextRecord(text);
} catch (UnsupportedEncodingException e) {
// should never happen unless we get a malformed tag.
throw new IllegalArgumentException(e);
}
} }
 <?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" > <EditText
android:id="@+id/edittext_beam_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入要传输的文本"/> <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>
 

14、NFC技术:使用Android Beam技术传输文本的更多相关文章

  1. NFC(13)使用Android Beam技术传输文件

    注意 Android Beam技术传输文件时nfc只负责连接两个手机,而传输文件实际是用蓝牙模块.且目前接收文件功能只是系统完成,不用自写个接收程序. 传输文件相关的重要api 从Android4.1 ...

  2. NFC(12)使用Android Beam技术传输文本数据及它是什么

    Android Beam技术是什么 Android Beam的基本理念就是两部(只能是1对1,不可像蓝牙那样1对多)NFC设备靠近时(一般是背靠背),通过触摸一部NFC设备的屏幕,将数据推向另外一部N ...

  3. 15、NFC技术:使用Android Beam技术传输文件

    传输文件的API 从Android4.1开始,NfcAdapter类增加了如下两个推送数据的方法. NfcAdapter.setBeamPushUris NfcAdapter.setBeamPushU ...

  4. Android NFC开发(一)——初探NFC,了解当前前沿技术

    Android NFC开发(一)--初探NFC,了解当前前沿技术 官方文档:http://developer.android.com/guide/topics/connectivity/nfc/ind ...

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

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

  6. [转载] Android逃逸技术汇编

    本文转载自: http://blogs.360.cn/360mobile/2016/10/24/android_escape/ 摘    要 传统逃逸技术涉及网络攻防和病毒分析两大领域,网络攻防领域涉 ...

  7. Android官方技术文档翻译——Gradle 插件用户指南(6)

    没想到翻译这篇<Gradle 插件用户指南>拖了差不多一个月,还跨年了.不过还好,在2号时终于一口气把剩下的给翻译完了(其实那天剩下的也就不到一章). 今天先发一下第六章,明天再发第七章. ...

  8. Android官方技术文档翻译——清单合并

    本文译自Android官方技术文档<Manifest Merger>,原文地址:http://tools.android.com/tech-docs/new-build-system/us ...

  9. Android官方技术文档翻译——迁移 Gradle 项目到1.0.0 版本

    本文译自Android官方技术文档<Migrating Gradle Projects to version 1.0.0>,原文地址:http://tools.android.com/te ...

随机推荐

  1. SWD接口:探索&泄密&延伸

    http://bbs.21ic.com/icview-871133-1-1.html 文买了个JLINKV9,以为神器,拿到手发现根本不是,完全没必要替换V8,想自己做个另类的调试器,当然想只是想而已 ...

  2. http://www.cnblogs.com/wzh206/archive/2010/03/21/1691112.html

    http://www.cnblogs.com/wzh206/archive/2010/03/21/1691112.html

  3. Oracle ->> 生成测试数据

    declare v_exists_table number; begin select count(*) into v_exists_table from all_tables where table ...

  4. Oracle ->> 随机函数

    SQL SERVER下生成随机数据干得多,可是到了Oracle下我就傻了.没用过Oracle,不知道该怎么办?SQL SERVER下依靠TABLESAMPLE或者CHECKSUM(NEWID())来做 ...

  5. storage size of ‘oldact’ isn’t known

    #include <signal.h> int main(){struct sigaction act, oldact;return 0;} dies with the message t ...

  6. Eclipse插件 —— Maven的安装

    1.下载插件 下载一(CSDN 网站下载) CSDN上提供的下载内容是笔者在SOURCEFORGE网站上下载下来的.        由于SOURCEFORGE网站上有多个版本,且没有集中打包,需逐个下 ...

  7. centos chrome

    在centos6.X和redhat enterprise 中安装chrome,我找了很久都不行,今天终于找到了可以用下脚本那安装: #! /bin/bash # Google Chrome Insta ...

  8. python之for学习

    for i in range(100,-1,-1): print "%s\n"%i; import os   path = 'D:\\Test'        for root, ...

  9. AIX 内存使用情况

    cat > WHAT_EVER_YOU_WANT.sh#!/usr/bin/ksh#memory calculatorum=`svmon -G | head -2|tail -1| awk {' ...

  10. linux学习之centos(二):虚拟网络三种连接方式和SecureCRT的使用

    ---操作环境--- 虚拟机版本:VMware Workstation_10.0.3 Linux系统版本:CentOS_6.5(64位) 物理机系统版本:win10  一.虚拟网络三种连接方式 当在V ...