/*
* Copyright 2011, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.nfc.demo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
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.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final String TAG = "stickynotes";
// private boolean mResumed = false;
private boolean mWriteMode = false;
NfcAdapter mNfcAdapter;
EditText mNote;
EditText mNoteRead;
PendingIntent mNfcPendingIntent;
IntentFilter[] mWriteTagFilters;
IntentFilter[] mNdefExchangeFilters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
setContentView(R.layout.main);
findViewById(R.id.write_tag).setOnClickListener(mTagWriter);
findViewById(R.id.read_tag).setOnClickListener(mTagRead);
mNote = ((EditText) findViewById(R.id.note));
mNote.addTextChangedListener(mTextWatcher);
mNoteRead = ((EditText) findViewById(R.id.noteRead));
// Handle all of our received NFC intents in this activity.
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Intent filters for reading a note from a tag or exchanging over p2p.
IntentFilter ndefDetected = new IntentFilter(
NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("text/plain");
} catch (MalformedMimeTypeException e) {
}
mNdefExchangeFilters = new IntentFilter[] { ndefDetected };
// Intent filters for writing to a tag
IntentFilter tagDetected = new IntentFilter(
NfcAdapter.ACTION_TAG_DISCOVERED);
mWriteTagFilters = new IntentFilter[] { tagDetected };
}
@Override
protected void onResume() {
super.onResume();
// mResumed = true;
// Sticky notes received from Android
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
NdefMessage[] messages = getNdefMessages(getIntent());
byte[] payload = messages[0].getRecords()[0].getPayload();
setNoteBody(new String(payload));
setIntent(new Intent()); // Consume this intent.
}
enableNdefExchangeMode();
}
@Override
protected void onPause() {
super.onPause();
// mResumed = false;
mNfcAdapter.disableForegroundNdefPush(this);
}
@Override
protected void onNewIntent(Intent intent) {
// NDEF exchange mode
if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] msgs = getNdefMessages(intent);
String body = new String(msgs[0].getRecords()[0].getPayload());
setNoteBody(body);
}
// Tag writing mode
if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(getNoteAsNdef(), detectedTag);
}
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
// if (mResumed) {
// mNfcAdapter.enableForegroundNdefPush(MainActivity.this, getNoteAsNdef());
// }
}
};
private View.OnClickListener mTagWriter = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Write to a tag for as long as the dialog is shown.
disableNdefExchangeMode();
enableTagWriteMode();
new AlertDialog.Builder(MainActivity.this).setTitle("Touch tag to write")
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
disableTagWriteMode();
enableNdefExchangeMode();
}
}).create().show();
}
};
private View.OnClickListener mTagRead = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Write to a tag for as long as the dialog is shown.
disableTagWriteMode();
enableNdefExchangeMode();
new AlertDialog.Builder(MainActivity.this).setTitle("Touch tag to read")
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
disableTagWriteMode();
enableNdefExchangeMode();
}
}).create().show();
}
};
private void setNoteBody(String body) {
Editable text = mNoteRead.getText();
text.clear();
text.append(body);
}
private NdefMessage getNoteAsNdef() {
byte[] textBytes = mNote.getText().toString().getBytes();
NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),
new byte[] {}, textBytes);
return new NdefMessage(new NdefRecord[] {
textRecord
});
}
NdefMessage[] getNdefMessages(Intent intent) {
// Parse the intent
NdefMessage[] msgs = null;
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
// Unknown tag type
byte[] empty = new byte[] {};
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] {
record
});
msgs = new NdefMessage[] {
msg
};
}
} else {
Log.d(TAG, "Unknown intent.");
finish();
}
return msgs;
}
private void enableNdefExchangeMode() {
mNfcAdap
- 1
- 2
前往页