2012-05-21 54 views
3

我的Android應用程序有兩項活動,一項主要用於信息,一項用於接收NFC。在NFC標籤上多次Android啓動活動

當啓動首次應用,我可以讀取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發起直接,沒有應用程式運行 - 日誌顯示它第一次工作,但第二次,沒有任何功能記錄任何東西。

謝謝你的任何有益的建議。

回答

9

我嘗試了一切後,最終找到了答案。

答案是設置活動到Android:launchmode =「singleTask」, 並在onNewIntent添加代碼行:

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

謝謝你,救了我的生活!!我有了有線行爲,即使沒有任何額外功能,也執行同樣的意圖。我真的不知道爲什麼這個意圖在內部得到了保存! – oli

+0

也爲我工作,謝謝!它需要是android:launchMode不是android:launchmode ... – IAmCoder