一、注册:
启动模式使用singleTask,避免每次打开新的activity
<activity
android:name=".nfc.AutoOpenUriActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.LAUNCHER" />
/>
</intent-filter>
</activity>
二、代码:
1、初始化NfcAdapter
2、在onresume时启动
mNfcAdapter.enableForegroundDispatch(this, mIntent, null, null);
3、在onpause时让其失效
mNfcAdapter.disableForegroundDispatch(this);
4、在onnewIntent时,获得Tag
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
然后写入数据
5、数据使用NdefMessage封装
6、通过tag获得ndef实现类,可以数据的写入数据
Ndef ndef = Ndef.get(tag);
package com.app.views.nfc;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.app.views.R;
import java.io.IOException;
public class AutoOpenUriActivity extends AppCompatActivity {
private NfcAdapter mNfcAdapter;
private PendingIntent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_open_uri);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
}
@Override
protected void onResume() {
super.onResume();
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeNFCTag(tag);
}
private void writeNFCTag(Tag tag) {
if (tag == null) return;
NdefMessage msg = new NdefMessage(new NdefRecord[]{NdefRecord.createUri(Uri.parse("http://www.baidu.com"))});
Ndef ndef = Ndef.get(tag);
try {
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) return;
if (ndef.getMaxSize() < msg.toByteArray().length) return;
ndef.writeNdefMessage(msg);
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
} else {
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable != null) {
formatable.connect();
formatable.format(msg);
Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "format error", Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}