如何设置一个NFC阅读器应用程序,如果该应用程序被关闭,它不会自己打开



我正在做这个应用程序,它应该读取一些nfc标签。

这是一种寻宝游戏,谁扫描了所有的标签谁就赢了。

我构建了应用程序,以便有一个初始登录和一组数据保存在数据库中,以便您可以跟踪扫描标签的玩家。

我按照教程创建了一个活动,可以读取标签. (从标签中只能读取一行文本)

这是我放在清单中的代码

<uses-permission android:name="android.permission.NFC"/>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain"/>
</intent-filter>

这是活动代码

公共类scanActivity扩展AppCompatActivity {

private TextView scanView;
private PendingIntent pendingIntent;
private IntentFilter[] readfilters;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scanView=findViewById(R.id.scanView);
try {
Intent intent= new Intent(this,getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter textFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED,"text/plain");
readfilters = new IntentFilter[] {intentFilter, textFilter};
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}

readTag(getIntent());
}
private void enableRead(){
NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,pendingIntent,readfilters,null);
}
private void disableRead(){
NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
}
@Override
protected void onResume() {
super.onResume();
enableRead();
}
@Override
protected void onPause() {
super.onPause();
disableRead();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
readTag(getIntent());
}
private void readTag(Intent intent) {
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
scanView.setText("");
if(messages != null){
for (Parcelable message:messages){
NdefMessage ndefMessage = (NdefMessage) message;
for (NdefRecord record : ndefMessage.getRecords()){
switch (record.getTnf()){
case NdefRecord.TNF_WELL_KNOWN:
scanView.append("WELL KNOWN ");
if (Arrays.equals(record.getType(),NdefRecord.RTD_TEXT)){
scanView.append("TEXT: ");
scanView.append(new String(record.getPayload()));
scanView.append("n");
}
}
}
}
}
}
}

目前,当我接近一个标签,手机试图打开一个任务,但它最终重新打开应用程序,它甚至不打开任务与textview上的标签的内容应该写入。

我需要确保当我接近一个标签时,应用程序不会再次重新打开,而是简单地切换到下一个活动,保持之前的.

另外,我想防止应用程序在接近标签时打开自己。

如果上述要求不可能。我至少需要能够创建一个活动,读取标签而不打开其他活动。

我提前感谢那些试图帮助我的人。

为了防止应用程序在接近标签时自动打开,请删除清单中的intent-filter条目

如果你不想在检测到标签时暂停并恢复活动,那么不要使用enableForegroundDispatch的旧NFC API,使用enabledReaderMode的更新更好的API,因为这会将标签数据传递给当前活动中的新线程,而无需暂停和恢复当前活动。

enableReaderMode的Java示例

相关内容

最新更新