【发布时间】:2015-06-02 14:40:17
【问题描述】:
我正在尝试将 NDEF 消息写入标签。以下是我拥有的代码。我在我的 IDE 中使用调试器运行代码,但在执行该行之后
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
tag 是null(我假设这意味着没有找到标签)并且我无法编写 NDEF 消息。相反,我得到了 NullPointerException。
public class MainActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
private NfcAdapter mNfcAdapter;
static final byte[] TYPE_BT_OOB = "application/vnd.bluetooth.ep.oob".
getBytes(Charset.forName("US_ASCII"));
private NdefMessage mNdefMessage;
String mLocalBluetoothAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNdefMessage = createHandoverRequestMessage();
Intent intent = getIntent();
//Intent intent = new Intent();
String action = intent.getAction();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);// I am getting only Null in tag here//
try {
Ndef ndef = Ndef.get(tag);
ndef.connect();
try {
ndef.writeNdefMessage(mNdefMessage);
} catch (FormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ndef.close();
} catch (IOException e) {
Log.e("TagDispatch", e.toString());
}
}
这是我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfcdemov5"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:debuggable="true" >
<activity
android:name="com.example.nfcdemov5.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:mimeType="application/vnd.bluetooth.ep.oob" />
</intent-filter>
</activity>
</application>
</manifest>
【问题讨论】:
-
您的标签上有哪些数据(之前)?您是通过点击标签开始活动还是您的活动已经在前台可见?你用
enableForegroundDispatch()吗?如果是,请显示相关代码(来自onResume()、onPause()、onNewIntent())。 -
感谢迈克尔的回复。标签没有任何数据。我唯一的目标是将 NDEF 写入标签。抱歉 - 我是应用程序开发和 NFC 的新手。
-
好吧,那你现在到底在做什么?您手动启动应用程序(通过单击启动器图标)?或者当您触摸标签时应用程序是否启动?当您触摸标签时,应用程序会执行任何操作吗?同样,这是您活动的所有代码还是还有更多?
-
除了上面给出的代码之外,我还有用于准备 NDEF 消息的代码 - createHandoverRequestMessage() 用于与蓝牙设备配对。我无法分享代码,因为它太长了。我尝试通过连接启用 NFC 的手机并将其放在我要编写 NDEF 消息的标签上来执行。它什么也没做。所以我尝试使用调试器ON。在 Tag(tag) 语句之后,一旦进入 try 部分,它就会抛出 nullexception 错误。当我检查标签的值时,它显示为空。
-
intent.getaction() 之后的动作是“android.intent.action.MAIN”。我不确定这是否会帮助你给我建议。
标签: android android-intent tags nfc ndef