2014-11-08 45 views
-1

我有一個標籤,其中包含Android Play應用的內容。當手機靠近它時,它會默認打開Android Play商店的應用程序頁面。 現在我想要做的是寫一個應用程序可以讀取這個標籤。所以我修改的AndroidManifest.xml如下:閱讀NFC標籤中包含Android Play應用的內容

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

     <intent-filter> 
      <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 
      <category android:name="android.intent.category.DEFAULT" /> 
      <data 
       android:host="ext" 
       android:pathPrefix="/android.com:pkg" 
       android:scheme="vnd.android.nfc" /> 
     </intent-filter> 
...... 

我用另一個標籤應用才能閱讀標籤,它有內容,如:

NDEF message 
EXTERNAL: urn:nfc:ext:android.com:pkg 
com.example.app 

我認爲最關鍵的一點是意圖過濾器。但是當我接近這個標籤時,我無法午餐。無論我的應用程序是在後臺還是前臺。有人可以幫助我嗎?謝謝。

+0

[檢查這一點,如果它有助於(http://stackoverflow.com/a/26698189/2591002),如果你有其他的應用程序,它也被註冊了同樣的行動,你會被給予對話來選擇你想要打開的應用程序。 – 2014-11-08 13:56:27

+0

在前臺沒有應用程序時,沒有對話選擇應用程序。我想如果幾個應用程序註冊了相同的Action,前臺應用程序將默認爲午餐。 – 2014-11-08 14:02:53

+0

但如果沒有應用程序在前臺,那麼它也打開應用程序(如果只有一個)或顯示對話..你檢查鏈接? – 2014-11-08 14:04:20

回答

0

我剛找到答案。我誤解了前景的意義,讓這款APP在前臺運行。它具有enableForegroundDispatch添加如下:

private NfcAdapter nfcAdapter; 
private PendingIntent mPendingIntent; 
private IntentFilter[] mFilters; 
private String[][] mTechLists; 

protected void onCreate(Bundle savedInstanceState) 
    nfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 
    IntentFilter ndefPkg = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); 
    try { 
     ndefPkg.addDataScheme("vnd.android.nfc"); 
     ndefPkg.addDataAuthority("ext", null); 
     ndefPkg.addDataPath("/android.com:pkg", 0); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    mFilters = new IntentFilter[] {ndefPkg; 
    mTechLists = new String[][] { new String[] { NfcF.class.getName() } }; 
} 

protected void onResume() { 
    super.onResume(); 
    nfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists); 
} 

protected void onPause() { 
    super.onPause(); 
    nfcAdapter.disableForegroundDispatch(this); 
}