Android Beam 详细实现步骤

2023-05-16

前言

       最近没怎么写东西了,主要是在了解Beam这个东东。找到一些高手写的文章,奈何水平有限看的云里雾里的。没办法,只好去复习官方文档。


正文: 

先摘取一部分官方文档:

Beaming NDEF Messages to Other Devices


Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The application that wants to beam data to another device must be in the foreground and the device receiving the data must not be locked. When the beaming device comes in close enough contact with a receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose whether or not to beam the message to the receiving device.

Note: Foreground NDEF pushing was available at API level 10, which provides similar functionality to Android Beam. These APIs have since been deprecated, but are available to support older devices. SeeenableForegroundNdefPush() for more information.

You can enable Android Beam for your application by calling one of the two methods:

An activity can only push one NDEF message at a time, so setNdefPushMessageCallback() takes precedence over setNdefPushMessage() if both are set. To use Android Beam, the following general guidelines must be met:

  • The activity that is beaming the data must be in the foreground. Both devices must have their screens unlocked.
  • You must encapsulate the data that you are beaming in an NdefMessage object.
  • The NFC device that is receiving the beamed data must support the com.android.npp NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange Protocol). The com.android.npp protocol is required for devices on API level 9 (Android 2.3) to API level 13 (Android 3.2). com.android.npp and SNEP are both required on API level 14 (Android 4.0) and later.

Note: If your activity enables Android Beam and is in the foreground, the standard intent dispatch system is disabled. However, if your activity also enables foreground dispatching, then it can still scan tags that match the intent filters set in the foreground dispatching.

To enable Android Beam:

  1. Create an NdefMessage that contains the NdefRecords that you want to push onto the other device.
  2. Call setNdefPushMessage() with a NdefMessage or call setNdefPushMessageCallback passing in aNfcAdapter.CreateNdefMessageCallback object in the onCreate() method of your activity. These methods require at least one activity that you want to enable with Android Beam, along with an optional list of other activities to activate.

    In general, you normally use setNdefPushMessage() if your Activity only needs to push the same NDEF message at all times, when two devices are in range to communicate. You usesetNdefPushMessageCallback when your application cares about the current context of the application and wants to push an NDEF message depending on what the user is doing in your application.

主要是理解上面这部分东西,多看即便会有不一样的感觉。

下面是我按照官方的例子调试出来的一篇Beam代码,功能和官方的一样。我还在完善,先贴出来,以后更新。

package com.example.beamtest;
/**
 * Time: 2012.8.11
 * Author: kehr
 * Aim: Test Android beam
 */
import java.nio.charset.Charset;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

public class Beam extends Activity implements CreateNdefMessageCallback {

	NfcAdapter mNfcAdapter;
	// TextView mEditText;
	EditText mEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// fullscreen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// no title
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.beam_layout);
		mEditText = (EditText) findViewById(R.id.beam_input_EditText);
		// 检测设备是否支持NFC
		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (mNfcAdapter == null) {
			Toast.makeText(this, "你的设备不支持", Toast.LENGTH_LONG).show();

			// 检测NFC是否开启
		} else if (mNfcAdapter.isEnabled()) {

			Toast.makeText(this, "NFC开启!", Toast.LENGTH_LONG).show();
		} else {

			Toast.makeText(this, "NFC未开启!请手动设置~", Toast.LENGTH_LONG).show();
		}

		// 注册回调函数
		mNfcAdapter.setNdefPushMessageCallback(this, this);
	}

	// 发送消息-------------------------------------------------------------------------
	// 这是CreateNdefMessageCallback中需要实现的方法
	@Override
	public NdefMessage createNdefMessage(NfcEvent event) {
		// TODO Auto-generated method stub
		// 获取文本框中的内容
		String text = mEditText.getText().toString();
		NdefMessage msg = new NdefMessage(new NdefRecord[] { createMimeRecord(
				"application/com.example.android.beam", text.getBytes()) });
		return msg;
	}

	public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
		byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
		NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
				mimeBytes, new byte[0], payload);
		return mimeRecord;
	}

	// 消息发送完成的处理------------------------------------------------
         //------------不是主要功能,官方例子里面有,我给去掉了----------------待实现……
	// 处理接收的消息----------------------------------------------------------------------
	// 第一步,接收Intent
	@Override
	protected void onNewIntent(Intent intent) {
		// super.onNewIntent(intent);

		setIntent(intent);
	}

	// 第二步,判断Intent
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
			processIntent(getIntent());
		}
	}

	// 第三步。处理Intent
	void processIntent(Intent intent) {
		Parcelable[] rawMsgs = intent
				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		// only one message sent during the beam
		NdefMessage msg = (NdefMessage) rawMsgs[0];
		// record 0 contains the MIME type, record 1 is the AAR, if present
		mEditText.setText(new String(msg.getRecords()[0].getPayload()));
	}

}

上面这是Beam实现的主代码,运行起来还需要一些其它的配置。

其实初步理解后发现,beam也没有想像中来的麻烦。

如果需要完整的工程文件,请留言联系我。

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android Beam 详细实现步骤 的相关文章

随机推荐

  • MySql学习笔记(三)MySql常用命令说明

    一 数据库命令 1 1显示数据库命令 命令 xff1a mysql gt show databases 执行后 xff1a 43 43 Database 43 43 information schema mysql performance
  • ubuntu 使用dpkg手动安装deb包时发生循环依赖的解决办法

    将循环依赖的所有包放到同一个命令行里一起安装 xff0c 如 xff1a sudo dpkg i libnss3 nssdb 3 28 4 0ubuntu0 14 04 4 all deb libnss3 3 28 4 0ubuntu0 1
  • 什么是源端口和目的端口

    源端口就是指本地端口 目的端口就是远程端口 一个数据包 xff08 pocket xff09 被解封装成数据段 xff08 segment xff09 后就会涉及到 连接上层协议的端口问题 很多人都在源端口和目的端口这两个概念上犯迷糊 xf
  • ini文件

    关于ini 文件的存储于加载 xff0c 初次遇到 xff0c 刚接触ini 文件 xff0c 我想我该把它记下 xff0c 以后提醒自己要常用 参数 保存 xff1a 参数结构体 struct TextConfig int nVol 音量
  • MIUI9线刷包精简

    MIUI9线刷包精简 1 说明 xff1a 系统包一经修改 xff0c 将无法通过OTA升级 xff08 可能只是修改system分区的无法OTA升级 xff0c 一般精简都修改system分区 xff0c system分区未修改的能不能O
  • logback高级特性使用(三)

    本文转自 xff1a 点击打开链接 异步记录日志 注意 xff1a 该功能需要高版本才能支持 xff0c 如1 0 11 AsyncAppender xff0c 异步记录日志 工作原理 xff1a 当Logging Event进入Async
  • spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)

    本文转自 xff1a 点击打开链接 SPRING官方网站改版后 xff0c 建议都是通过 Maven和Gradle 下载 xff0c 对不使用 Maven和Gradle 开发项目的 xff0c 下载就非常麻烦 xff0c 下给出Spring
  • ThreadLocal是否会引起内存溢出?

    本文参考 xff1a 点击打开链接 最近碰到一个使用ThreadLocal时因为未调用remove 而险些引起内存溢出的问题 xff0c 所以看了下ThreadLocal的源码 xff0c 结合线程池原理做一个简单的分析 xff0c 确认是
  • JS判断日期范围(日期范围应在一个月之内)

    本文转自 xff1a 点击打开链接 之前的一个项目的日期选择功能由单个日期 xff0c 修改为日期范围 xff0c 用到了日期范围的判断 xff0c 使用JS实现 xff0c 希望对需要的人有所帮助 代码如下 xff1a var start
  • python视频教程大全集下载啦

    本文转自 xff1a 点击打开链接 python3英文视频教程 全87集 http pan baidu com s 1dDnGBvV python从入门到精通视频 xff08 全60集 xff09 链接 xff1a http pan bai
  • 如何关闭ubuntu alt快捷键

    本文转自 xff1a 点击打开链接 有时候发现ubuntu的alt快捷键真是太烦人了 xff0c 动不动就能把搜索框呼唤出来 xff0c 尤其是我在ubuntu上装了win7虚拟机 xff0c 喜欢用qq的alt 43 s发送消息 xff0
  • ubuntu安装原生迅雷,让下载成为简单

    今天想到电影天堂下点电影 xff0c 发现TM全都是迅雷链接 xff0c 旋风链接什么的 无奈自带的BT下载器速度又慢 xff0c 又满足不了日常的一些文件下载 于是乎google了下 xff0c 哎呀 xff0c 有个mldonkey的电
  • Android 采用fastboot刷system.img boot.img recovery.img’

    手机正常启动后 xff0c 命令行模式下输入 adb reboot bootloader 该命令会自动进入fastboot模式 接着 xff1a fastboot devices 查看是否有设备 erase 擦除的意思 xff0c 你懂得
  • Executors.newSingleThreadExecutor的一些坑

    还是直接上源码吧 public static ExecutorService newSingleThreadExecutor return new FinalizableDelegatedExecutorService new Thread
  • 学习AOP之透过Spring的Ioc理解Advisor

    本文转自 xff1a 点击打开链接 花了几天时间来学习Spring xff0c 突然明白一个问题 xff0c 就是看书不能让人理解Spring xff0c 一方面要结合使用场景 xff0c 另一方面要阅读源代码 xff0c 这种方式理解起来
  • 计算广告资料汇总

    papers 计算广告论文 学习资料 业界分享 王喆Paper Collection of Real Time Bidding Weinan Zhang计算广告干货整理 雪伦 在线课程 Introduction to Computation
  • 编辑器之神-vim的使用技巧

    vim VS emacs vim被誉为编辑器之神 xff0c 而emacs被誉为神之编辑器 中国文化博大精深 xff0c 他们究竟有什么区别呢 xff1f 作为emacs小白的我来说不想在这里献丑 xff0c 直接贴上一篇博客 xff0c
  • Linux离线环境安装bzip2

    1 下载离线安装包 bzip2 1 0 6 13 el7 x86 64 rpm http mirror centos org centos 7 os x86 64 Packages bzip2 1 0 6 13 el7 x86 64 rpm
  • Vivado使用与注意事项

    作者 QQ群 xff1a 852283276 微信 xff1a arm80x86 微信公众号 xff1a 青儿创客基地 B站 xff1a 主页 https space bilibili com 208826118 DRC INBB 3 Bl
  • Android Beam 详细实现步骤

    前言 最近没怎么写东西了 xff0c 主要是在了解Beam这个东东 找到一些高手写的文章 xff0c 奈何水平有限看的云里雾里的 没办法 xff0c 只好去复习官方文档 正文 xff1a 先摘取一部分官方文档 xff1a Beaming N