Android NFC Startup屏幕

时间:2012-03-19 18:07:51

标签: android broadcast nfc

当我点击我的应用上的按钮时,我正在尝试读取NFC标签。目前,我能够在默认模式下检测标签(在Nexus手机中安装标签应用程序)。但是我无法显示我想要启动标签的活动选择器

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 个答案:

答案 0 :(得分: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的onReceive方法中拥有的代码移动到NFC_button活动的onCreate。

如果您没有特别的理由想要使用BroadcastReceiver,这将解决您的标签阅读问题。

相关问题