Android Beam 详细实现步骤

前言

       最近没怎么写东西了,主要是在了解Beam这个东东。这方面的教程真的非常有限,找了不少资料目前还没看到一篇能够让一个新手看一遍就知道实现一个Beam功能都需要那些步骤的。而且,都是用的官方的例子,稍加注释。偶尔找到一些高手写的文章,奈何水平有限看的云里雾里的。没办法,只好去复习官方文档。

      都说现在Android方面的书没有什么很好的。我的体会是,书讲的都很全面,力求把每个方面都介绍一遍。这样带来的缺点是知识太浅,不够灵活。不过,想想书名也便释然了——“××Android 入门基础×× ”再加一些修饰词。唉~,入门~

正文: 

好了进入正题。看官方文档有些吃力,主要都是英文的,概念方面还有不足。但是坚持看下来还是有很大的收获的。


先摘取一部分官方文档:

 

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也没有想像中来的麻烦。

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
内容推荐   《Android 4高级编程(第3版)》由Android权威专家编写,涵盖了所有最新的内容,是学习使用Android 4SDK开发移动应用程序的理想指南。本书见解深刻,帮助经验丰富的Android开发人员充分挖掘Android4的新特性的潜力,同时讲解了Android开发的基础知识,使初学者也可以借助本书入门。作为一本以实用性为目的的指导图书,本书带领您逐步完成复杂程度越来越高的Android项目,每个项目中都引入一种新的Android平台特性,并着重指出有助于编写引人入胜的应用程序的技术和最佳实践。   《Android 4高级编程(第3版)》特色   ◆ 深入分析了Android应用程序的组件和生命周期   ◆ 探讨了AndroidUI原理、设计理念和UI API,使用户界   面在手机、平板电脑和电视上都引人注目   ◆ 介绍了创建基于地图的应用程序和使用基于位置的服务   的相关知识   ◆ 解释了如何创建后台服务、通知和Cloud to Device Messaging   ◆ 演示了如何创建动态的、交互式的主屏幕微件和Live   Wallpaper   ◆ 探索了硬件和通信API,包括蓝牙、电话、Wi-Fi Direct、   NFCAndroid Beam   ◆ 讲解了摄像头和硬件传感器的使用   ◆ 详述了新的动画框架和其他增强用户体验的特性,包括   拖放、Action Bar和Fragment   ◆ 新增了关于应用程序发布的一章内容   ◆ 介绍了License Verification和应用程序内收费服务 作者简介   Reto Meier,目前是Google Android 团队的一名Android 开发人员倡导者,帮助Android开发人员创建最优秀的应用程序。Reto 是一位经验丰富的软件开发人员,拥有逾10 年的GUI 应用程序开发经验。进入Google之前,他曾在多种行业中工作过,包括海洋石油、天然气以及金融业。   Reto 始终不渝地追求掌握新技术,从2007 年Android 发布之初Reto 就迷恋上了此项技术。 目录 第1章 Android简介 第2章 开始入手 第3章 创建应用程序和Activity 第4章 创建用户界面 第5章 Intent和Broadcast Receiver 第6章 使用Internet资源 第7章 文件、保存状态和首选项 第8章 数据库和Content Provider 第9章 在后台操作 第10章 扩展用户体验 第11章 高级用户体验 第12章 硬件传感器 第13章 地图、地理编码和基于位置的服务 第14章 个性化主屏幕 第15章 音频、视频以及摄像头的使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值