我有这段代码,我总是得到Ndef ndef = Ndef.get(tag) == null。我试着以不同的方式得到它,但我总是在那里得到null,在同一个地方。有人知道我做错了什么吗?
private ImageView imgSearch;
private NfcAdapter mAdapter;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc);
}
@Override
protected void onResume() {
super.onResume();
mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
//nfc not support your device.
Toast.makeText(this, R.string.no_nfc_supported, Toast.LENGTH_SHORT).show();
} else {
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
@Override
protected void onPause() {
super.onPause();
if (mAdapter != null) {
mAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
getTagInfo(intent);
}
private void getTagInfo(Intent intent) {
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
NdefMessage ndefMesg = ndef.getCachedNdefMessage();
if (ndefMesg != null) {
Toast.makeText(this, ndefMesg.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}在舱单里我有:
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />以及:
<activity android:name=".activities.NFCActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>发布于 2015-11-21 08:48:22
您正在使用前台分发系统来获得有关新标记的通知。
mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);当您将null作为意图筛选器和技术列表参数(最后两个参数)传递时,您的活动将在它处于前台时得到有关任何标记的通知。因此,在方法getTagInfo() (或实际上是onNewIntent())中,您将收到一个ACTION_TAG_DISCOVERED意图。
private void getTagInfo(Intent intent) {
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
// this part is executed, hence, you received an ACTION_TAG_DISCOVERED intent
}
}这意味着无论标记支持什么标记技术,getTagInfo()中的代码都将被执行。因此,如果标记不支持Ndef标记技术,Ndef.get(tag)将返回null。
您可以使用以下方法获得标记支持的技术列表:
String[] techList = tag.getTechList();如果标记不支持Ndef标记技术,这可能意味着该标记尚未配置为携带NDEF有效负载,必须首先使用NdefFormatable技术初始化(“格式化”)。
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
NdefMessage ndefMesg = ndef.getCachedNdefMessage();
if (ndefMesg != null) {
...
}
} else {
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable != null) {
// initialize tag with new NDEF message
try {
ndefFormatable.connect();
ndefFormatable.format(newNdefMessage);
} finally {
try {
ndefFormatable.close();
} catch (Exception e) {}
}
}
}但是,如果标记既不支持Ndef也不支持NdefFormatable,这意味着标记不是nor标记,根本不支持携带NDEF有效负载。
https://stackoverflow.com/questions/33784218
复制相似问题