读书人

向Tag写下数据

发布时间: 2013-06-26 14:29:32 作者: rapoo

向Tag写入数据
在Activity中检测移动设备是否支持NFC

??????? android.nfc.NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
??? ??? if (nfcAdapter == null); //This device doesn't support NFC!

检测移动设备是否打开NFC功能,如果没有打开,跳转到setting page

?????? if (!nfcAdapter.isEnabled()) {
?? ??? ??? ?final Intent openTagIntent = new Intent(Settings.ACTION_NFC_SETTINGS);
?? ??? ??? ?openTagIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
?? ??? ??? ?startActivity(openTagIntent);?? ??? ??
?? ??? ?}

?

在onNewIntent方法中初始化要写入数据的tagandroid.nfc.Tag tag =? intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);写入数据

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

??? private Button btnOperateTag;
??? private EditText editTagMessage;
??? private NfcAdapter adapter;
??? private PendingIntent pendingIntent;
??? private Tag mytag;
??? private IntentFilter writeTagFilters[];
??? private Context context;

??? private static final String tag = "MainActivity";

??? @Override
??? protected void onCreate(Bundle savedInstanceState) {
??? ??? super.onCreate(savedInstanceState);
??? ??? setContentView(R.layout.activity_main);
??? ??? context = getApplicationContext();

??? ??? btnOperateTag = (Button) findViewById(R.id.btn_operate_tag);
??? ??? editTagMessage = (EditText) findViewById(R.id.edit_message);
??? ??? adapter = NfcAdapter.getDefaultAdapter(this);
??? ??? pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
??? ??? IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
??? ??? tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
??? ??? writeTagFilters = new IntentFilter[] { tagDetected };
??? ??? btnOperateTag.setOnClickListener(new Button.OnClickListener() {
??? ??? ??? @Override
??? ??? ??? public void onClick(View v) {
??? ??? ??? ??? String message = editTagMessage.getText().toString();
??? ??? ??? ??? if (message.trim().length() < 4) {
??? ??? ??? ??? ??? Toast.makeText(context, "Please enter more than 3 characters.", Toast.LENGTH_LONG).show();
??? ??? ??? ??? } else {
??? ??? ??? ??? ??? try {
??? ??? ??? ??? ??? ??? if (mytag == null) {
??? ??? ??? ??? ??? ??? ??? Toast.makeText(context, "Tag Not Detected. Where Do You Want Write?", Toast.LENGTH_SHORT).show();
??? ??? ??? ??? ??? ??? } else {
??? ??? ??? ??? ??? ??? ??? write(message, mytag);
??? ??? ??? ??? ??? ??? ??? Toast.makeText(context, "I Have Written Your First Tag!", Toast.LENGTH_SHORT).show();
??? ??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? } catch (IOException e) {
??? ??? ??? ??? ??? ??? Toast.makeText(context, "Error During Writing. Are You Sure That Your Tag Is Close To Your Mobile Phone?", Toast.LENGTH_LONG).show();
??? ??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? ??? } catch (FormatException e) {
??? ??? ??? ??? ??? ??? Toast.makeText(context, "A invalid format.", Toast.LENGTH_LONG).show();
??? ??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? ??? }
??? ??? ??? ??? }
??? ??? ??? }
??? ??? });
??? ??? Log.d(tag, "-------------Create-----------------");
??? }

??? @Override
??? protected void onNewIntent(Intent intent) {
??? ??? if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
??? ??? ??? ??? || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
??? ??? ??? mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
??? ??? ??? if (mytag != null) {
??? ??? ??? ??? Toast.makeText(context, mytag.toString(), Toast.LENGTH_SHORT).show();
??? ??? ??? ??? if(btnOperateTag != null){
??? ??? ??? ??? ??? btnOperateTag.setEnabled(true);
??? ??? ??? ??? }
??? ??? ??? }
??? ??? ??? Log.d(tag, "-------------New Inent-----------------");
??? ??? }
??? }

??? private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
??? ??? String lang = "en";
??? ??? byte[] textBytes = text.getBytes();
??? ??? byte[] langBytes = lang.getBytes("UTF-8");
??? ??? int langLength = langBytes.length;
??? ??? int textLength = textBytes.length;???
??? ??? byte[] payload = new byte[1 + langLength + textLength];

??? ??? // set status byte (see NDEF spec for actual bits)
??? ??? payload[0] = (byte) langLength;

??? ??? // copy langbytes and textbytes into payload
??? ??? System.arraycopy(langBytes, 0, payload, 1, langLength);
??? ??? System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

??? ??? NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);

??? ??? return recordNFC;
??? }

??? private void write(String text, Tag tag) throws IOException, FormatException {

??? ??? NdefRecord[] records = { createRecord(text) };
??? ??? NdefMessage message = new NdefMessage(records);
??? ??? // Get an instance of Ndef for the tag.
??? ??? Ndef ndef = Ndef.get(tag);
??? ??? if (ndef != null) {
??? ??? ??? // Enable I/O
??? ??? ??? ndef.connect();
??? ??? ??? // Write the message
??? ??? ??? ndef.writeNdefMessage(message);
??? ??? ??? // Close the connection
??? ??? ??? ndef.close();
??? ??? } else {
??? ??? ??? NdefFormatable format = NdefFormatable.get(tag);
??? ??? ??? if (format != null) {
??? ??? ??? ??? try {
??? ??? ??? ??? ??? format.connect();
??? ??? ??? ??? ??? format.format(message);
??? ??? ??? ??? ??? Log.e(this.tag,"Formatted tag and wrote message");

??? ??? ??? ??? } catch (IOException e) {
??? ??? ??? ??? ??? Log.e(this.tag,"Failed to format tag.");
??? ??? ??? ??? }
??? ??? ??? } else {
??? ??? ??? ??? Log.e(this.tag,"Tag doesn't support NDEF.");
??? ??? ??? }
??? ??? }
??? }

??? @Override
??? public void onPause() {
??? ??? super.onPause();
??? ??? WriteModeOff();
??? }

??? @Override
??? public void onResume() {
??? ??? super.onResume();
??? ??? WriteModeOn();
??? }

??? private void WriteModeOn() {???
??? ??? adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
??? }

??? private void WriteModeOff() {
??? ??? adapter.disableForegroundDispatch(this);
??? }
}

?

读书人网 >移动开发

热点推荐