2012-03-19 148 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