gpt4 book ai didi

Android 在 NFC 标签上多次启动 Activity

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:02 26 4
gpt4 key购买 nike

我的 Android 应用程序有 2 个 Activity,一个主要用于信息,一个用于接收 NFC。

首次启动该应用时,我可以多次读取 NFC 标签 - 每次都启动一个新 Activity 并显示一些信息。

如果应用程序关闭但手机被带到 NFC 标签 - 它会第一次显示 nfc 标签 Activity ,但再也不会响应任何其他标签。

我做错了什么?!

第二个 Activity 的 list 部分和代码:

<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />

<application
android:icon="@drawable/aaa"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">

<activity
android:label="@string/app_name"
android:name=".MainActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".TagDiscoveredActivity"
android:screenOrientation="portrait">
<intent-filter >
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/filter_nfc" />
</activity>
</application>

</manifest>

代码

public class TagDiscoveredActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
etc
}

@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
resolveIntent(intent);
}

private void resolveIntent(Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//| Intent.FLAG_ACTIVITY_SINGLE_TOP);

boolean handled = false;

// Parse the intent
final String action = intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {

// When a tag is discovered we send it to the service to be save. We
// include a PendingIntent for the service to call back onto. This
// will cause this activity to be restarted with onNewIntent(). At
// that time we read it from the database and view it.
Parcelable nfctag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (nfctag != null) {
//read tag and display here
}
}
}

if (!handled) {
Log.e(logTag, "Unknown intent " + intent);
finish();
return;
}
}

当我运行它并记录第二种情况时 - 直接从 NFC 启动而不运行应用程序 - 日志显示它第一次工作,但第二次,没有任何功能记录任何内容。

感谢您提供任何有用的建议。

最佳答案

千方百计终于找到了答案。

答案是设置activity为android:launchmode="singleTask",并在 onNewIntent 的代码中添加以下行:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

关于Android 在 NFC 标签上多次启动 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10687482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com