NFC广播问题

3

我已经阅读了大约10到20个关于这方面的主题,但不幸的是我没有成功地使它工作。我的接收器可以捕获广播,但只能通过sendBroadcast(intent)从我的应用程序发送它才可以。我想让它从NFC适配器中捕获广播。例如,有人把NFC标签放在我的设备附近,然后我的应用程序应该启动或显示在浏览菜单中,但这并没有发生。即使我的应用程序启动,并且我将NFC标签放在设备附近,它也无法捕获它,在浏览菜单中我看到其他可以的应用程序。

我的接收器:

public class SomeBroadcastReceiver extends BroadcastReceiver {
private final String TAG = "SomeBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Got intent: " + intent);    
}
}    

我的清单文件如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.nfc">
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name">

<receiver android:enabled="true" android:name=".broadcast.SomeBroadcastReceiver">
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        <category android:name="android.intent.category.DEFAULT" />

            <action android:name="android.nfc.action.TECH_DISCOVERED"/>
        <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/technologies"/>

        <action android:name="android.nfc.action.TAG_DISCOVERED"/>
</intent-filter>        
</receiver>

<activity android:name=".simulator.FakeTagsActivity"
    android:theme="@android:style/Theme.NoTitleBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name="TagViewer"
    android:theme="@android:style/Theme.NoTitleBar">
    <intent-filter>
      <action android:name="android.nfc.action.TAG_DISCOVERED" />
      <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>        
</activity>

</application>
<uses-sdk android:minSdkVersion="10" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />

在FakeActivity中,我有以下代码:

Intent exampleIntent = new Intent("android.nfc.action.NDEF_DISCOVERED"); sendBroadcast(exampleIntent);

当应用程序执行到这些代码时,我的接收器会捕获intent,因此我认为接收器没问题,但是也许我在清单文件中漏掉了一些东西?是否需要特殊权限来捕获全局广播?或者我需要启动服务或其他什么东西吗?


你找到这个问题的解决方案了吗? - Antonio
3个回答

7

你不能使用BroadcastReceiver来捕获这些意图,因为只有活动可以接收NFC意图。您可以在 NFC指南中找到更多信息。


1
根据这里 (https://dev59.com/CW445IYBdhLWcg3wcaAN#5320694) 的说法,你不能通过BroadcastReceiver来捕获NFC意图。唯一的处理方式是通过ForegroundDispatch和activity内的onNewIntent()函数。当NFC标签被触发时,它会查找前台活动以处理它。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接