Ste*_*ick 4 tags android nfc ndef android-applicationrecord
我想使用NFC标签启动应用程序.我使用Android应用程序记录(AAR)使用Android应用程序记录(AAR),使用NFC标签启动Android应用程序,使用额外数据或使用NDEF_DISCOVERED/ TECH_DISCOVEREDintent过滤器.但是,在通过NFC事件启动时,如何将NFC标签(例如某些文本)中的数据传递给我的活动?
我已经阅读了NFC基础知识,但据我所知,它似乎想要实现一种读取标签的机制,当我真的不想在标签打开应用程序后重新读取标签,但是相反,我只想要同时传入的数据.
此外,这些机制似乎允许应用程序在标记启动后读取标记.换句话说,我担心如果有人在应用程序打开后再点击标签,那么标签将再次被读取(这是我不想要的).
其次,我如何创建这样的NDEF消息?
Android会自动读取NFC标签的NDEF消息并进行处理
为了让您的活动开始并让Android传递预读取的NDEF消息,您可以使用NDEF_DISCOVEREDintent过滤器:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="vnd.android.nfc"
android:host="ext"
android:pathPrefix="/example.com:mycustomtype"/>
</intent-filter>
Run Code Online (Sandbox Code Playgroud)
然后从您的活动中,您可以处理该NDEF消息:
public void onResume() {
super.onResume();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
NdefMessage[] msgs = null;
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];
}
}
if ((msgs != null) && (msgs.length > 0)) {
NdefRecord[] records = msgs[0].getRecords();
NdefRecord firstRecord = records[0];
byte[] payloadData = firstRecord.getPayload();
// do something with the payload (data passed through your NDEF record)
// or process remaining NDEF message
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,onResume()只要您的活动成为前台活动,就会运行.因此,对于相同的标签,它可能会运行多次.因此,您可以使用其他生命周期方法,也可以采取一些不会多次解析消息的预防措施.
如果您想放弃所有进一步的NFC活动,一旦您的活动开放,您可以按照我所描述的方法响应Android应用仅为一个活动启用NFC.因此,您将注册前台调度(这使您的活动优先接收NFC事件,然后您可以简单地删除这些事件.
public void onResume() {
super.onResume();
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
public void onPause() {
super.onPause();
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
}
public void onNewIntent(Intent intent) {
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
// drop NFC events
}
}
Run Code Online (Sandbox Code Playgroud)
最后,要为NFC标签创建NDEF消息,您可以执行以下操作:
byte[] payload = ... // generate your data payload
NdefMessage msg = new NdefMessage(
NdefRecord.createExternal("example.com", "mycustomtype", payload)
)
Run Code Online (Sandbox Code Playgroud)
如果您想确保只有您的应用是通过此标记启动的(或者如果没有为您的应用打开Play Store,则还可以添加AAR:
NdefMessage msg = new NdefMessage(
NdefRecord.createExternal("example.com", "mycustomtype", payload),
NdefRecord.createApplicationRecord("com.example.your.app.package")
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3344 次 |
| 最近记录: |