2013年1月28日星期一
NFC相关技术及手机架构分析
一、NFC手机硬件架构
实现NFC功能的手机终端硬件架构至少包含NFC控制器、安全模块、天线、应用处理器等模块。
1、控制器(NFCControUer):NFC控制器集成在终端的主板上,负责将数字信号转换为射频信号,并通过13.56MHz天线发送;同时负责接收射频信号,并将其转为数字信号,与终端应用处理器和安全模块进行通信。
2安全模块:用于存储用户的敏感数据(如密钥、余额等)和卡模拟模式下相关的NFC应用,通过NFC控制器与外界读写设备进行通信,实现数据存储及交易过程的安全性。
3天线:集成在终端内部,与NFC控制器相连接,实现13.56M射频信号的发射与接收。
4应用处理器:NFC终端的主控模块,实现对NFC控制器的控制和操作及与SIM卡间的数据交互。应用处理器中运行NFC协议栈软件及各种应用程序,实现NFC应用的处理与展现。
二、NFC手机软件架构
NFC手机软件架构是由NFC的协议栈、NFCAPI及应用组成。
1、NFC协议栈
实现NFC相关协议的分析处理。包括硬件抽象层(HAL),操作系统抽象层(OSAL),传输控制层(TCL)和NFC核心功能(NFCCore)。
硬件抽象层(HAL):对不同的硬件接口进行抽象封装,并向上层提供统一的接口。
操作系统抽象层(OSAL):对不同平台的05资源进行抽象封装,并向整个协议栈提供统一的接口,如内存管理、消息处理等。
传输控制层(TCL):架构于HAL硬件抽象层之上,包括逻辑链路控制、数据传输等功能。
NFC核心功能(NFCCore):实现NFC核心协议,并向上层提供统一的接口。包括格式分析处理,发现注册机制等。
2、NFCAPI
根据不同的操作系统及中间件,向上层应用提供接口。在JAVA虚拟机上使用JSR257及相应扩展,在Android操作系统上使用Andro记NFCAPI及相应扩展。
3、NFC应用
NFC终端应用,包括卡模拟应用,读写器应用,点对点应用三种工作模式。
卡模式:是指用于非接触移动支付,如商场、交通等应用中,用户只需要将手机靠近读卡器,然后用户只需输入密码确认交易或者直接接收交易即可。例如门禁管制,车票,门票等等。这种方式下,卡片通过非接触读卡器的即域来供电,即便是手机没电也可以工作。卡模式如
读卡器模式:即作为非接触读卡器使用,比如从海报或者展览信息电子标签上读取相关信息
点对点模式:即实现无线数据交换,将两个具备NFC功能的设备链接,能实现数据点对点传输,如下载音乐,交换图片或者同步设备地址薄。因此多个设备比如数字相机、PDA、计算机及手机之间都可以通过NFC来无线连通,交换资料或者服务。
工作模式中的通信模式分为了主动模式和被动模式。卡模式是主动模式,读卡器模式是被动模式。
三、NFC与手机的结合方式
1、与手机SIM卡结合
NFC可以说是手机内SIM(subseriberIdentityModule)卡的另一个延伸介面,SIM卡本体性质上是一种接触性的智能卡且仅与手机接触连接,而NFC技术却让SIM卡从原有的接触介面再延伸出另一个非接触的无线感应介面。但是这个技术涉及到与不同的SIM卡运营商标准化的问题。
2、硬件NFC芯片
直接将NFC芯片焊接在手机主板上,成本低,不涉及统一标准的问题。
Android NFC 开发教程概述(转载)
Near Field Communication (NFC) 为一短距离无线通信技术,通常有效通讯距离为4厘米以内。NFC工作频率为13.65 兆赫兹,通信速率为106 kbit/秒到 848kbit/秒。
NFC通信总是由一个发起者(initiator)和一个接受者(target)组成。通常initiator 主动发送电磁场(RF)可以为被动式接受者(passive target)提供电源。其工作的基本原理和收音机类似。正是由于被动式接受者可以通过发起者提供电源,因此target 可以有非常简单的形式,比如标签,卡,sticker 的形式。
NFC 也支持点到点的通信(peer to peer) 此时参与通信的双方都有电源支持。
和其它无线通信方式如Bluetooth相比,NFC 支持的通信带宽和距离要小的多,但是它成本低,如价格标签可能只有几分钱,也不需要配对,搜寻设备等,通信双方可以在靠近的瞬间完成交互。
在Android NFC 应用中,Android手机通常是作为通信中的发起者,也就是作为NFC 的读写器。Android手机也可以模拟作为NFC通信的接受者且从Android 2.3.3起也支持P2P通信。
Android对NFC的支持主要在 android.nfc 和android.nfc.tech 两个包中。
android.nfc 包中主要类如下:
NfcManager 可以用来管理Android设备中指出的所有NFC Adapter,但由于大部分Android设备只支持一个NFC Adapter,可以直接使用getDefaultAapater 来获取系统支持的Adapter。
NfcAdapter 为一NFC Adapter 对象,可以用来定义一个Intent使系统在检测到NFC Tag时通知你定义的Activity,并提供用来注册forground tag 消息发送的方法等。
NdefMessage 和NdefRecord NDEF 为NFC forum 定义的数据格式。
Tag 代表一个被动式Tag对象,可以代表一个标签,卡片,钥匙扣等。当Android设备检测到一个Tag时,会创建一个Tag对象,将其放在Intent对象,然后发送到相应的Activity。
android.nfc.tech 中则定义了可以对Tag进行的读写操作的类,这些类按照其使用的技术类型可以分成不同的类如:NfcA, NfcB, NfcF,以及MifareClassic 等。
常见的Tag为Mifare ,后面的例子将以这种Tag 为例介绍NFC读写方法。
本例参考ApiDemos中NFC的ForegoundDispatch来介绍编写Android NFC 的基本步骤,因为手边只有MifareClassic 类型的Tag ,需要对ForegoundDispatch的代码做些修改来检测MifareClassic 的类型的NFC Tag,读写其他类型的NFC Tag的基本步骤是一致的。
1. 在Android manifest 文件中申明和NFC相关的权限和功能选项:
权限申明:
<uses-permission android:name=”android.permission.NFC” />
最低版本要求,NFC是指Android2.3 (Level 10) 才开始支持的,因此最低版本要求必须指定为10.
<uses-sdk android:minSdkVersion=”10″/>
如果需要在Android Market上发布,需要指定手机支持NFC 功能。
<uses-feature android:name=”android.hardware.nfc” android:required=”true” />
为Activity申明它支持处理NFC Tag
比如我们的示例Activity 在Manifest 的申明如下:
<activity android:name=”.NFCDemoActivity”
android:label=”@string/app_name”
android:launchMode=”singleTop”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
<intent-filter>
<action android:name=”android.nfc.action.NDEF_DISCOVERED”/>
<data android:mimeType=”text/plain” />
</intent-filter>
<intent-filter>
<action
android:name=”android.nfc.action.TAG_DISCOVERED”
>
</action>
<category
android:name=”android.intent.category.DEFAULT”
>
</category>
</intent-filter>
<!– Add a technology filter –>
<intent-filter>
<action android:name=”android.nfc.action.TECH_DISCOVERED” />
</intent-filter>
<meta-data android:name=”android.nfc.action.TECH_DISCOVERED”
android:resource=”@xml/filter_nfc”
/>
</activity>
三种Activity NDEF_DISCOVERED ,TECH_DISCOVERED,TAG_DISCOVERED 指明的先后顺序非常重要, 当Android设备检测到有NFC Tag靠近时,会根据Action申明的顺序给对应的Activity 发送含NFC消息的 Intent.
2. Android NFC 消息发送机制
当Android设备检测到有NFC Tag时,理想的行为是触发最合适的Activity来处理检测到的Tag,这是因为NFC通常是在非常近的距离才起作用(<4m) ,如果此时需要用户来选择合适的应用来处理Tag,很容易断开与Tag之间的通信。因此你需要选择合适的Intent filter 只处理你想读写的Tag类型。
Android系统支持两种NFC消息发送机制:Intent 发送机制和前台Activity 消息发送机制。
Intent 发送机制 当系统检测到Tag时,Android系统提供manifest 中定义的Intent filter 来选择合适的Activity来处理对应的Tag,当有多个Activity可以处理对应的Tag类型时,则会显示Activity选择窗口由用户选择:
前台Activity 消息发送机制 允许一个在前台运行的Activity在读写NFC Tag 具有优先权,此时如果Android检测到有NFC Tag ,如果前台允许的Activity可以处理该种类型的Tag则该Activity具有优先权,而不出现Activity 选择窗口。
这两种方法基本上都是使用Intent-filter 来指明Activity可以处理的Tag类型,一个是使用Android的Manifest 来说明,一个是通过代码来申明。
下图显示当Android检测到Tag,消息发送的优先级:
本例 NFCDemoActivity 支持两种NFC消息发送机制,上面的XML指明了Intent 消息发送机制,其中
<meta-data android:name=”android.nfc.action.TECH_DISCOVERED”
android:resource=”@xml/filter_nfc”/>
的filter_nfc 指明了支持处理的NFC Tag类型,filter_nfc.xml 定义如下:
<resources xmlns:xliff=”urn:oasis:names:tc:xliff:document:1.2″>
<!– capture anything using NfcF –>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
<tech>android.nfc.tech.MifareClassic</tech>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
因为我只有MifareClassic 类型的Tag,所以只定义了MifareClassic相关的Tag类型,如果你可以处理所有Android支持的NFC类型,可以定义为:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
<tech>android.nfc.tech.NfcA</tech>
<tech>android.nfc.tech.NfcB</tech>
<tech>android.nfc.tech.NfcF</tech>
<tech>android.nfc.tech.NfcV</tech>
<tech>android.nfc.tech.Ndef</tech>
<tech>android.nfc.tech.NdefFormatable</tech>
<tech>android.nfc.tech.MifareClassic</tech>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
有了这个Manifest中的申明,当Android检测到有Tag时,会显示Activity选择窗口,如上图中的Reading Example。
当NFCDemoActiviy在前台运行时,我们希望只有它来处理Mifare 类型的Tag,此时可以使用前台消息发送机制,下面的代码基本和ApiDemos中的NFC示例类似:
public class NFCDemoActivity extends Activity {
private NfcAdapter mAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private TextView mText;
private int mCount = 0;
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.foreground_dispatch);
mText = (TextView) findViewById(R.id.text);
mText.setText("Scan a tag");
mAdapter = NfcAdapter.getDefaultAdapter(this);
// Create a generic PendingIntent that will be deliver
// to this activity. The NFC stack
// will fill in the intent with the details of the
//discovered tag before delivering to
// this activity.
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Setup an intent filter for all MIME based dispatches
IntentFilter ndef
= new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] {
ndef,
};
// Setup a tech list for all MifareClassic tags
mTechLists
= new String[][] { new String[] { MifareClassic.class.getName() } };
}
@Override
public void onResume() {
super.onResume();
mAdapter.enableForegroundDispatch(this,
mPendingIntent, mFilters, mTechLists);
}
@Override
public void onNewIntent(Intent intent) {
Log.i("Foreground dispatch",
"Discovered tag with intent: " + intent);
mText.setText("Discovered tag " +
++mCount + " with intent: " + intent);
}
@Override
public void onPause() {
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
}
只改了一行,将处理NfcF类型的Tag 改为处理MifareClassic 类型的NFC Tag。
mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };
运行该示例,每靠近一次Tag,计数加1。
前面例子介绍了检测,读写NFC TAG开发的一般步骤,本例针对常用的Mifare Tag 具体说明。
Mifare Tag 可以有1K ,2K, 4K,其内存分区大同小异,下图给出了1K字节容量的Tag的内存分布:
数据分为16个区(Sector) ,每个区有4个块(Block) ,每个块可以存放16字节的数据,其大小为16 X 4 X 16 =1024 bytes
每个区最后一个块称为Trailer ,主要用来存放读写该区Block数据的Key ,可以有A,B两个Key,每个Key 长度为6个字节,缺省的Key值一般为全FF或是0. 由 MifareClassic.KEY_DEFAULT 定义。
因此读写Mifare Tag 首先需要有正确的Key值(起到保护的作用),如果鉴权成功
auth = mfc.authenticateSectorWithKeyA(j,
MifareClassic.KEY_DEFAULT);
然后才可以读写该区数据。
本例定义几个Mifare相关的类 MifareClassCard ,MifareSector, MifareBlock 和MifareKey 以方便读写Mifare Tag.
Android 系统来检测到NFC Tag, 将其封装成Tag类,存放到Intent的NfcAdapter.EXTRA_TAG Extra 数据包中,可以使用MifareClassic.get(Tag) 获取对象的 MifareClassic类。
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // 4) Get an instance of the Mifare classic card from this TAG // intent MifareClassic mfc = MifareClassic.get(tagFromIntent);
下面为读取Mifare card 的主要代码:
// 1) Parse the intent and get the action that triggered this intent
String action = intent.getAction();
// 2) Check if it was triggered by a tag discovered interruption.
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// 3) Get an instance of the TAG from the NfcAdapter
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// 4) Get an instance of the Mifare classic card from this TAG
// intent
MifareClassic mfc = MifareClassic.get(tagFromIntent);
MifareClassCard mifareClassCard=null;
try { // 5.1) Connect to card
mfc.connect();
boolean auth = false;
// 5.2) and get the number of sectors this card has..and loop
// thru these sectors
int secCount = mfc.getSectorCount();
mifareClassCard= new MifareClassCard(secCount);
int bCount = 0;
int bIndex = 0;
for (int j = 0; j < secCount; j++) {
MifareSector mifareSector = new MifareSector();
mifareSector.sectorIndex = j;
// 6.1) authenticate the sector
auth = mfc.authenticateSectorWithKeyA(j,
MifareClassic.KEY_DEFAULT);
mifareSector.authorized = auth;
if (auth) {
// 6.2) In each sector - get the block count
bCount = mfc.getBlockCountInSector(j);
bCount =Math.min(bCount, MifareSector.BLOCKCOUNT);
bIndex = mfc.sectorToBlock(j);
for (int i = 0; i < bCount; i++) {
// 6.3) Read the block
byte []data = mfc.readBlock(bIndex);
MifareBlock mifareBlock = new MifareBlock(data);
mifareBlock.blockIndex = bIndex;
// 7) Convert the data into a string from Hex
// format.
bIndex++;
mifareSector.blocks<i> = mifareBlock;
}
mifareClassCard.setSector(mifareSector.sectorIndex,
mifareSector);
} else { // Authentication failed - Handle it
}
}
ArrayList<String> blockData=new ArrayList<String>();
int blockIndex=0;
for(int i=0;i<secCount;i++){
MifareSector mifareSector=mifareClassCard.getSector(i);
for(int j=0;j<MifareSector.BLOCKCOUNT;j++){
MifareBlock mifareBlock=mifareSector.blocks[j];
byte []data=mifareBlock.getData();
blockData.add("Block "+ blockIndex++ +" : "+
Converter.getHexString(data, data.length));
}
}
String []contents=new String[blockData.size()];
blockData.toArray(contents);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contents));
getListView().setTextFilterEnabled(true);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
showAlert(3);
}finally{
if(mifareClassCard!=null){
mifareClassCard.debugPrint();
}
}
}
</i>
Android中NFC功能流程图解析及代码演示
Android中NFC功能流程图解析及代码演示
在Android4.0推出的时候,一个非常引人注目的功能就是NFC(Near Field Communication).
参考文章:
Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.
翻译:
近场通讯(NFC)是一系列短距离无线技术,一般需要4cm或者更短去初始化连接。近场通讯(NFC)允许你在NFC tag和Android设备或者两个Android设备间共享小负载数据。
近场通讯(NFC)是一系列短距离无线技术,一般需要4cm或者更短去初始化连接。近场通讯(NFC)允许你在NFC tag和Android设备或者两个Android设备间共享小负载数据。
典型的应用为刷卡应用,如刷信用卡,公交车卡,吃饭的饭卡之类。腾讯2011年1月份文章“Android首款NFC近场通信应用推出”,说明了基于Android的NFC应用目前已经有了,得益于日本在手机刷卡的应用氛围。据2011年7月网易文章“PayPal推出Android系统NFC移动支付服务”报道,PayPal已经做了尝试了,相信这股风很快要刮到中国。
下面我们从技术的层面来分析一下这个技术。相关的类代码有:NfcAdapter,NdefMessage, NdefRecord,ACTION_TAG_DISCOVERED.
下面我们从技术的层面来分析一下这个技术。相关的类代码有:NfcAdapter,NdefMessage, NdefRecord,ACTION_TAG_DISCOVERED.
在功能层面上,涉及到了NFC的读写功能。下面我们分别来做总结。
在代码层上面:
使用的时候,需要在AndroidManifest.xml里面加一些权限以及属性。
<uses-permission android:name="android.permission.NFC"/> <uses-feature android:name="android.hardware.nfc" android:required="true"/> <uses-sdk android:minSdkVersion="10"/>
这里注意,在Android Version 9的时候仅仅支持了ACTION_TAG_DISCOVERED,对于其他的需要10以上。
在上面的基础上,还需要增加intent-filter的支持。
<intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter>
获取NfcAdapter的代码为
public static String getStatusNfcDevice () { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(); if (nfcAdapter.isEnabled()) { String status = "enabled"; return status; } else { String status = "disabled"; return status; } }
处理函数为
public void onResume() { super.onResume(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } } //process the msgs array }
完整的一个操作代码摘自Google Android NFC Guide代码(略加注释):
package com.example.android.beam; 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.widget.TextView; import android.widget.Toast; import java.nio.charset.Charset; //继承并实现接口CreateNdefMessageCallback方法createNdefMessage public class Beam extends Activity implements CreateNdefMessageCallback { NfcAdapter mNfcAdapter; TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView = (TextView) findViewById(R.id.textView); // Check for available NFC Adapter //检测是否有NFC适配器 mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show(); finish(); return; } // Register callback //注册回调函数 mNfcAdapter.setNdefPushMessageCallback(this, this); } @Override public NdefMessage createNdefMessage(NfcEvent event) { String text = ("Beam me up, Android!\n\n" + "Beam Time: " + System.currentTimeMillis()); //回调函数,构造NdefMessage格式 NdefMessage msg = new NdefMessage( new NdefRecord[] { createMimeRecord( "application/com.example.android.beam", text.getBytes()) /** * The Android Application Record (AAR) is commented out. When a device * receives a push with an AAR in it, the application specified in the AAR * is guaranteed to run. The AAR overrides the tag dispatch system. * You can add it back in to guarantee that this * activity starts when receiving a beamed message. For now, this code * uses the tag dispatch system. */ //,NdefRecord.createApplicationRecord("com.example.android.beam") }); return msg; } @Override public void onResume() { super.onResume(); // Check to see that the Activity started due to an Android Beam //得到是否检测到ACTION_NDEF_DISCOVERED触发 if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { processIntent(getIntent()); } } //重载Activity类方法处理当新Intent到来事件 @Override public void onNewIntent(Intent intent) { // onResume gets called after this to handle the intent setIntent(intent); } /** * Parses the NDEF Message from the intent and prints to the TextView */ //关键处理函数,处理扫描到的NdefMessage void processIntent(Intent intent) { textView = (TextView) findViewById(R.id.textView); 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 textView.setText(new String(msg.getRecords()[0].getPayload())); } /** * Creates a custom MIME type encapsulated in an NDEF record */ 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; } }
上面代码还需要在AndroidManifest.xml文件里面添加
<intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="application/com.example.android.beam"/> </intent-filter>
在对NFC设备进行写操作的时候,相关代码:
private void enableTagWriteMode() { mWriteMode = true; IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); mWriteTagFilters = new IntentFilter[] { tagDetected }; mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null); }
@Override protected void onNewIntent(Intent intent) { // Tag writing mode if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (NfcUtils.writeTag(NfcUtils.getPlaceidAsNdef(placeidToWrite), detectedTag)) { Toast.makeText(this, "Success: Wrote placeid to nfc tag", Toast.LENGTH_LONG) .show(); NfcUtils.soundNotify(this); } else { Toast.makeText(this, "Write failed", Toast.LENGTH_LONG).show(); } } }
/* * Writes an NdefMessage to a NFC tag*/ public static boolean writeTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { return false; } if (ndef.getMaxSize() < size) { return false; } ndef.writeNdefMessage(message); return true; } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); return true; } catch (IOException e) { return false; } } else { return false; } } } catch (Exception e) { return false; } }
相关的AndroidManifest.xml文件配置如下:
<activity android:name=".CheckInActivity"> <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <data android:mimeType="application/vnd.facebook.places"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity>
参考文章:
参考文章:
http://developer.android.com/guide/topics/nfc/nfc.html
http://stackoverflow.com/questions/5078649/android-nfc-sample-demo-reads-only-fake-information-from-the-tag
http://developer.android.com/guide/topics/nfc/index.html
http://money.163.com/11/0714/09/78TPVJOL00253CVK.html
http://www.cnblogs.com/jfttcjl/archive/2011/11/09/2242045.html
http://www.jessechen.net/blog/how-to-nfc-on-the-android-platform/
另外有几个专门推动NFC技术的联盟:
http://open-nfc.org/wp/nfchal/
http://www.classic.nxp.com/theme/nfc/
http://www.nfc-forum.org/home/
官方关于NFC的翻译文档见:
http://blog.csdn.net/nicebooks/article/details/6223956
参考库:
http://code.google.com/p/guava-libraries/
Android 2.3加入了NFC(近场通讯)的支持
Android 2.3加入了NFC(近场通讯)的支持。官网developer.android.com的英文介绍如下:
Near Field Communications (NFC)
Android 2.3 includes an NFC stack and framework API that lets developers read NDEF tags that are discovered as a user touches an NFC-enabled device to tag elements embedded in stickers, smart posters, and even other devices.
The platform provides the underlying NFC services that work with the device hardware to discover tags when they come into range. On discovering a tag, the platform notifies applications by broadcasting an Intent, appending the tag's NDEF messages to the Intent as extras. Applications can create Intent filters to recognize and handle targeted tags and messages. For example, after receiving a tag by Intent, applications extract the NDEF messages, store them, alert the user, or handle them in other ways.
The NFC API is available in the android.nfc package. The key classes are:
NfcAdapter, which represents the NFC hardware on the device.
NdefMessage, which represents an NDEF data message, the standard format in which "records" carrying data are transmitted between devices and tags. Applications can receive these messages from ACTION_TAG_DISCOVERED Intents.
NdefRecord, delivered in an NdefMessage, which describes the type of data being shared and carries the data itself.
NFC communication relies on wireless technology in the device hardware, so support for the platform's NFC features on specific devices is determined by their manufacturers. To determine the NFC support on the current device, applications can call isEnabled() to query the NfcAdapter. The NFC API is always present, however, regardless of underlying hardware support.
To use the NFC API, applications must request permission from the user by declaring <uses-permission android:name="android.permission.NFC"> in their manifest files.
Additionally, developers can request filtering on Android Market, such that their applications are not discoverable to users whose devices do not support NFC. To request filtering, add <uses-feature android:name="android.hardware.nfc" android:required="true"> to the application's manifest.
NFC的应用场景有很多,但Android 2.3目前API只提供了电子标签阅读器的功能。相信随着Android的版本升级,后续会增加很多应用场景和 API。
功能是少一点,但从无到有的第一步总是不容易的。从架构上看,至少有以下几部分的改动:
Android Framework层,为应用开发增加了相关API(即英文中的framework API)。
协议层,增加NFC的协议栈(即英文中的NFC Stack)。
硬件适配层,为硬件生产商提供适配接口,此层应该与NFC硬件的 Linux驱动通讯(实现方式待验证)。
工作流程是当支持NFC功能的手机或其他电子终端(后面简称手机)在用户开启NFC功能的时候,如果手机内置的NFC扫描器(相当于类NfcAdapter的功能)扫描到电子标签后,就会向相关用户程序发送ACTION_TAG_DISCOVERED的Intent,Itent的 extras架构中会包含NDEF(NFC Data Exchange Format)消息。如何处理此NDEF消息,就是用户程序的事情了。
NFC的API在android.nfc的包中提供,这个包主要提供三个大类,其中:NfcAdapter描述的就是手机中的NFC硬件,Android 2.3中可以暂时理解为电子标签扫描器。电子标签和扫描器中的消息通过NdefMessage来表示,这个类很简单,只是封装了NdefRecord。每个NdefMessage中可以包含多个NdefRecord,通过类NdefMessage的方法getRecords() 可以查询到消息的所有NdefRecord。NdefRecord才是信息的真正载体,正确理解这个类是理解NFC技术的一个重点。NFC的技术规范[url=link.php?url=http://www.nfc-forum.org%2Fspecs%2Fspec_list%2F]http://www.nfc-forum.org/specs/spec_list/[/url]是理解这个类不可或缺的资料。
应用程序的编程思路是:
通过android.nfc.NfcAdapter.getDefaultAdapter() 取得手机的objNfcAdapter
通过objNfcAdapter.isEnabled()查询该手机是否支持NFC
如果手机支持NFC,就申请接收ACTION_TAG_DISCOVERED 的Intent
如果接收到ACTION_TAG_DISCOVERED,就提取NdefMessage,并在此基础上进而提取 NdefRecord,整个是一个消息解析过程
2013年1月27日星期日
启用压缩提高SSH代理的速度
SSH代理是完全加密且可以压缩的,网上的介绍里面一般并没有启用压缩.在软件的SSH选项卡中,有个compression,把其中的zlib勾选,这样软件就支持SSH压缩 了,传输速度会进一步提高.
服务器端的配置这里也发下,自己有VPS的朋友也可以设置下,速度提升比较明显
echo "Compression yes" >> /etc/ssh/sshd_config
/etc/init.d/sshd restart
实测速度提升三倍左右.
原文:http://briteming.blogspot.com/2012/09/ssh.html
当Note2遇上NFC
话说,这个世界是由懒人驱动的。 什么?你不信?
世界上的很多发明,都是因为懒人而来的……
懒得爬楼梯,于是人们发明了电梯……
懒得走路,于是人们制造了汽车、火车和飞机……
懒得每次去计算,于是人们发明了计算机……
懒得出去听音乐会,于是人们发明了CD、随身听和各种数码影音设备……
说了这么多,其实是想向大家介绍一下Note2的一项新功能:NFC,当Note2遇上了NFC,又会为我这样的懒人,带来什么样的便利呢?
开始之前,先得介绍介绍什么是NFC,这是来自网上的一段解释:
近场通信(Near Field Communication,NFC),又称近距离无线通信,是一种短距离的高频无线通信技术,允许电子设备之间进行非接触式点对点数据传输(在十厘米内)交换数据。这个技术由免接触式射频识别(RFID)演变而来,并向下兼容RFID,最早由Sony和Philips各自开发成功,主要用于手机等手持设备中提供M2M(Machine to Machine)的通信。由于近场通讯具有天然的安全性,因此,NFC技术被认为在手机支付等领域具有很大的应用前景。
其实集成NFC技术的手机,早已应用在SONY的智能手机上了。 三星的Note2,也刚好集成了这项技术。 要想使用NFC,必须得手机先支持NFC,然后去万能的淘宝,购入几个NFC标签即可。一般每个NFC标签的价格在3~4块左右,不贵。
如上图,就是我在淘宝买的4个标签,这标签估计是和SONY的手机配套的,淘宝上有商家单卖。
用NFC标签,配合Android上各种丰富的应用,就能实现很多的功能,这简直就是我这个懒人的福音啊。
假设有一个这样的场景,当你刚进入办公室,为了在工作时间接听电话不会影响到其他的同事,你通常会把手机设置成振动模式。又或者你想在办公室用公司的WIFI上网,这时候会通常会怎么做呢?对于一般的Android系统,你通常会从屏幕上方开始向下滑动,拖出那个Android特有的消息通知系统,通过按图标的方式,把WIFI打开,然后点几下按钮,把手机调成振动。想到这一些列的动作,是不是觉得很麻烦呢?有了NFC标签,你就可以省去这一系列的操作了,直接把手机往贴在办公室柜子上的NFC标签靠一下,一切就设置好了。
又假设你刚下班回家,坐上车,想把手机重新从振动模式调回成响铃模式,还想把在办公室里面打开的WIFI关掉,另外,还想匹配一下车上的蓝牙耳机。不得不承认,这又是一系列的操作,多麻烦啊……还好,有了NFC,你只需要把手机往贴在车上的NFC标签一靠,就一切妥当了。这真是太方便了!
又假如,回到家,进入客厅,你想重新打开wifi,并且把响铃模式打开,其实只需要靠一下家里门口的NFC标签,就可以了。
夜深了,你打算休息了,想关闭WIFI,又或者设定明天的闹钟,又或者想把手机设置成静音模式,也只需要把手机往床头柜上的NFC标签靠一下,就可以了。
举了这么多个例子,不知道你理解到NFC给你带来的方便没有,其实,这些都不是假设,这些例子,哥已经应用到我的工作和生活中了……
Android上有很多支持NFC的应用,我就是用了一款叫做”NFC任务启动器”的软件来实现上面的各种功能。
软件方便的列出了各种可以定制的任务,从打开/关闭 蓝牙、WIFI、各种任务可供你定制,满足你的需求。同时可以让你方便的管理各个NFC标签,非常方便。
当然,NFC的应用还远不止这些,网上还有很多应用,可以支持通过NFC读取公交卡的余额和消费明细,等等。(现在的很多公交卡其实也是用的NFC技术实现的)
如果你的手机也支持NFC,或者你也用Note2,千万别荒废了这个方便的功能哦!
freevpnhosting提供免费美国VPN
作为站长,用到vpn的时候还挺多,虽然不是干什么特别的事情,但是,很多网站需要vpn才能正常。苦逼的站长,不想花钱,就得话费时间辛苦的寻找免费vpn了。其实,提供免费vpn的网站还是很多的,而提供免费的目的也是为了推销他的收费vpn,因为免费vpn是有使用限制的,比如半小时换次密码、用户多网速慢、限制下载等等。所以,如果要求不是很高的话,免费vpn还是可以用用的,否则,还是买收费vpn吧。这个免费vpn是美国的,话说很多vpn都是美国的,呵呵,人家有钱呗。
好了,上vpn免费网站了:http://freevpnhosting.com/
打开网页后,点击上图中的Get ACCESS Now(或者网页往下拉)就能看到如下信息:
vpn密码需要半小时变更一次,所以,需要到网站再获取一次。
订阅:
博文 (Atom)