[英]Android launch activity multiple times on an NFC tag
我的Android應用程序有2個活動,一個主要用於信息活動,另一個用於接收NFC。
首次啟動該應用程序時,我可以多次讀取NFC標簽-每次都啟動一個新活動並顯示一些信息。
如果應用已關閉,但手機已帶至NFC標簽-它將首次顯示nfc標簽活動,但永遠不會再響應任何其他標簽。
我究竟做錯了什么?!
清單部分和第二個活動的代碼:
<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啟動-日志顯示它是第一次運行,但是第二次,沒有任何功能記錄任何東西。
感謝您提供任何有用的建議。
經過一切嘗試,我終於找到了答案。
答案是將活動設置為android:launchmode =“ singleTask”,然后在onNewIntent中的代碼中添加以下行:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.