2012-03-19 90 views
1

我試圖閱讀NFC標籤,當我點擊我的應用程序上的按鈕時。目前,我可以在默認模式下檢測標籤(安裝在Nexus手機中的標籤應用程序)。但我不能夠得到顯示,通過它我想啓動我的標籤活動選擇器Android NFC啓動屏幕

public class NFC_button extends Activity 
{ 

protected IntentFilter ifilter ; 
private NfcAdapter adapter; 

private BroadcastReceiver receiver = new BroadcastReceiver() 
{ 

    @Override 
    public void onReceive(Context context, Intent intent) 
    { 

     if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) 
     { 
      Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
      NdefMessage[] ndefmessages; 
      if(messages != null) 
      { 
       ndefmessages = new NdefMessage[messages.length]; 

       for(int i = 0;i<messages.length;i++) 
       { 
        ndefmessages[i] = (NdefMessage)messages[i]; 
       } 



      } 

     } 

    } 
}; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    adapter=NfcAdapter.getDefaultAdapter(this); 


    ifilter = new IntentFilter(); 
    ifilter.addAction("android.nfc.action.NDEF_DISCOVERED"); 
    ifilter.addCategory("android.intent.category.LAUNCHER"); 

} 



@Override 
protected void onResume() { 
    registerReceiver(receiver, ifilter); 

super.onResume(); 
} 




} 

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.nfc.example" 
android:versionCode="1" 
android:versionName="1.0" > 

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

<uses-sdk android:minSdkVersion="10"/> 

<application 

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

    <activity android:name=".NFC_button"> 

     </activity> 

</application> 

回答

1

首先把我不認爲BroadcastReciver是讀取標籤的正確方法。和其他錯誤,我看到的是,你的意圖過濾器有一個類別:

android.intent.category.LAUNCHER 

但正確的類別應該是:

android.intent.category.DEFAULT 

我建議你的意圖過濾器添加到的清單要活動開始,當你觸摸這樣的標籤:

<activity android:name=".NFC_button"> 
<intent-filter > 
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/> 
    <category android:name="android.intent.category.DEFAULT"/> 
</intent-filter> 
</activity> 

和移動自己的BroadcastReceiver中向NFC_butt的的onCreate的方法的onReceive有碼活動。

如果沒有特定的原因要使用BroadcastReceiver,這將解決您的標籤閱讀問題。

+0

你能解釋一下爲什麼你不認爲BroadcastReceiver是讀取標籤的正確方法嗎?考慮我的用例:我正在將數據寫入標籤。我希望用戶準備數據,然後將標籤貼近設備,以便在檢測到標籤時寫入數據。我不想啓動一個活動(更改用戶界面),因爲用戶正在進行其他活動,使他們的數據準備好寫入。 – wsgeorge 2017-03-24 10:30:58