我建议创建一个在清单中注册的 BroadcastReceiver。这将允许您的应用程序即使没有运行也能收到通知。
public class NfcReceiver extends BroadcastReceiver {
/* ... */
@Override
public void onReceive(Context context, Intent intent) {
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];
}
}
} /* end handle NDEF_DISCOVERED */
} /* end onReceive */
} /* end BroadcastReceiver*/
在您的清单中,请务必添加正确的意图过滤器(我从未做过 NFC,但我相信这对您来说是正确的:)
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<uses-sdk android:minSdkVersion="10"/>
<uses-permission android:name="android.permission.NFC" />
<receiver android:name=".NfcReceiver">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>
</receiver>
http://developer.android.com/guide/topics/connectivity/nfc/nfc.html
http://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html
如果您可以/希望走这条路,也有一些解决方案,例如:
http://mobisocial.github.com/EasyNFC/apidocs/reference/mobisocial/nfc/Nfc-source.html