1. 程式人生 > >Android Beam 詳細實現步驟

Android Beam 詳細實現步驟

前言

       最近沒怎麼寫東西了,主要是在瞭解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. See for more information.

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

  • : Accepts an  to set as the message to beam. Automatically beams the message when two devices are in close enough proximity.
  • : Accepts a callback that contains a  which is called when a device is in range to beam data to. The callback lets you create the NDEF message only when necessary.

An activity can only push one NDEF message at a time, so  takes precedence over  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  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  that contains the s that you want to push onto the other device.
  2. Call  with a  or call  passing in a 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  if your Activity only needs to push the same NDEF message at all times, when two devices are in range to communicate. You use 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也沒有想像中來的麻煩。

如果需要完整的工程檔案,請留言聯絡我。

相關推薦

Android Beam 詳細實現步驟

前言        最近沒怎麼寫東西了,主要是在瞭解Beam這個東東。找到一些高手寫的文章,奈何水平有限看的雲裡霧裡的。沒辦法,只好去複習官方文件。 正文:  先摘取一部分官方文件: Beaming NDEF Messages to Other Devices A

Android-X5WebView詳細整合步驟

本文意在瞭解掌握並快速整合騰訊X5系統核心,更好的提高Android與H5在應用上的渲染互動效果;X5web核心下該如何有效的管理cookie;X5webview下的ndk基本配置說明;X5webview常見問題等等。 Android-X5WebView封裝(含Cookie管理、進度監聽、適配8

Android Studio 快速實現上傳專案到Github(詳細步驟

前言: 本文主要講解如何將Android Studio專案上傳至GitHub,在此之前,先介紹幾個概念。 Android Studio:是谷歌推出一個Android整合開發工具,基於IntelliJ IDEA,類似 Eclipse ADT,Android Studio 提供了整合的 Android 開發工具用

Android開發分享功能實現步驟

集成 sha har sse 分享 功能 秘鑰 步驟 過去 參考mob官網(http://www.mob.com/) 分享實現步驟:1.mob官網賬號註冊登錄2.進入後臺,進入ShareSDK,添加應用,生成秘鑰3.參照mob官網集成文檔,下載SDK,進入ShareSDK

Android進階:步驟四:Android 接入百度地圖API 基礎實現

內容概括: 註冊申請百度地圖開發平臺賬號 這裡是地址  如何申請百度地圖的賬號也有官方文件:在這裡 申請祕鑰(AK)、快速獲取釋出版SHA1和測試版SHA1和包名 (文件裡面也有如果建立應用以及申請的教程,但在Android Studio中實現更加簡單) 百度地

高德地圖開發(一)詳細配置步驟實現顯示簡單地圖

建立專案根據專案的包名和SHA1值去高德地圖平臺申請key值 包名  :  在build.gradle裡面或者AndroidManifest.xml裡面都能獲取到 SHA1值  :  參考:https://blo

Android 清除快取詳細實現(顯示快取大小)

  清除快取功能算是個十分雞肋的功能了,但是大多數產品或者客戶都希望有這麼個東西顯得APP功能完善,網上有很多,但是對於新手來說,那些感覺並不詳細,我貼個完整到小白都能懂的。 下面是工具類,包含清除快取、獲取快取檔案大小、格式化方法。 總之就是工具,自己建立一個帖進去。 p

哈夫曼壓縮演算法C語言實現——步驟詳細註釋原始碼

哈夫曼壓縮演算法的詳細實現步驟: 1、定義哈夫曼樹節點,用結構體。 2、利用C語言檔案讀寫,統計字元個數。 3、根據字元個數建立哈夫曼樹(不懂haffman資料結構的自己查下資料,我這裡就不再重複了) 4、根據哈夫曼樹為每個出現的字元編碼 5、壓縮:這裡涉及到位操作,用ch

android的APP呼叫C語言的動態連結庫的實現步驟

1.新建一個類test,通過System.loadLibrary()的方式將so載入進去,注意不要帶有lib 和 so 比如libhello.so,為System.loadLibrary(hello),如下文所示,JAVA 呼叫addtest,返回的Addtest為jn

詳細分析小米搶購軟體的實現步驟

1 init: function() { 2 this.inTheQueue = !1, 3 this.phoneSku = "", 4 this.phoneType = "", 5 this.hdinfoData = nu

android 檢查網路連線狀態實現步驟

獲取網路資訊需要在AndroidManifest.xml檔案中加入相應的許可權。  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 1)判斷是否有網路連線  複製程式碼程式碼如下: publ

酷炫開源專案cardsui-for-android-超詳細原始碼分析,詳解所用特效是如何實現

以下是我擷取的2個圖片,可以自定義成Card形式的View,佈局可以自己設定。點選露出來的部分可以使點選的Card滑落到下面,也可以左右滑動刪除Card。效果非常好        這篇文章主要寫下通過原始碼分析一下幾個地方是怎麼實現的。 Card的View和佈局 相互疊

Android Toolbar的詳細使用步驟

Toolbar 可以實現所有 ActionBar 的功能,並且可定製性更高。Toolbar 是 App 實現 Material Design 不可缺少的控制元件。 一、基礎使用 1.首先在 build.gradle 引入support v7包

Android OpenGL ES2.0 實現步驟

定義頂點資料 頂點資料描述了OpenGL世界中元素的位置,下面定義了繪製一個三角形所需要的頂點資料,x,y,z對應三角形的每個頂點座標,其中z代表深度,x1,y1對應著色器的顏色程式碼。 float vertices[] = {

rsync---全網備份---實現步驟

服務器 防火墻 server 系統管理員 配置文件 具體要求如下:1)所有服務器的備份目錄必須都為/backup2)要備份的系統配置文件包括但不限於: a.定時任務服務的配置文件(/var/spool/cron/root)(適合web和nfs服務器) b.開機自啟動的配

SVN trunk(主線) branch(分支) tag(標記) 用法詳解和詳細操作步驟

trac load mar span 必須 最可 objc copy 右鍵 原文地址:http://blog.csdn.net/vbirdbest/article/details/51122637 使用場景: 假如你的項目(這裏指的是手機客戶端項目)的某個版本(例如1.0

Spark SQL 源代碼分析之Physical Plan 到 RDD的詳細實現

local 過濾 右連接 操作 images img mem sans 觀察 /** Spark SQL源代碼分析系列文章*/ 接上一篇文章Spark SQL Catalyst源代碼分析之Physical Plan。本文將介紹Physical Plan的toRDD的

AndroidAndroid聊天機器人實現

小米 div bottom 曾經 圖靈 .9.png sdn http 歡迎界面 昨天看到一個Android視頻教程講圖靈機器人。那個API接口用起來還是挺方便的,就準備自己動手做一個了。另外自己還使用了高德地圖的API接口用於定位(曾經用過高德的接口,比X度方便) 大

zabbix3.0.4使用percona-monitoring-plugins插件來監控mysql5.6的詳細實現過程

sta moni nod .rpm exp oss percona 密碼 slave zabbix3.0.4使用percona-monitoring-plugins插件來監控mysql5.6的詳細實現過程 因為Zabbix自帶的MySQL監控沒有提供可以直接使用的Key,所

NFC技術:使用Android Beam技術傳輸文件(二)

imp 圖片 .com fault gen catch ret generate puts 1 public class MainActivity extends ActionBarActivity implements 2 CreateBeamUr