Skip to content

Instantly share code, notes, and snippets.

@junichim
Last active September 14, 2020 10:35
Show Gist options
  • Save junichim/cdfac06cfee913d05af927aa5937e6f1 to your computer and use it in GitHub Desktop.
Save junichim/cdfac06cfee913d05af927aa5937e6f1 to your computer and use it in GitHub Desktop.
NFC 書き込みサンプル

ブログ記事

【Android】 NFC を試しました

で使ってる NFC 書き込みサンプルの Gist

書籍『NFC Hacks』(株式会社ブリリアントサービス著, オライリージャパン発行)の Hack #35 を参考にして作成

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/id_editText"
android:layout_width="match_parent"
android:layout_height="0dp"
android:hint="enter id"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="no"
android:inputType="number" />
<EditText
android:id="@+id/note_editText"
android:layout_width="match_parent"
android:layout_height="45dp"
android:hint="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/id_editText"
android:autofillHints="no"
android:inputType="text" />
<Button
android:id="@+id/writeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/note_editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfcwriterexample">
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
<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="text/plain" />
</intent-filter>
-->
</activity>
</application>
</manifest>
package com.example.nfcwriterexample;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
/**
* 書籍 『NFC Hacks』 (株式会社ブリリアントサービス著, オライリージャパン発行)の Hack #35 を参考に作成した
* NFC書き込みアプリのサンプル実装
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private NfcAdapter mNfcAdapter;
private EditText mId;
private EditText mText;
private IntentFilter[] mNdefFilters;
private boolean mWriteFlag;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mId = (EditText) findViewById(R.id.id_editText);
mText = (EditText) findViewById(R.id.note_editText);
Button mButton = (Button) findViewById(R.id.writeButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Button#onClick");
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mNdefFilters = new IntentFilter[] {filter};
enableNdefMode(mNdefFilters);
new AlertDialog.Builder(MainActivity.this).setTitle("書き込みモード")
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
disableNdefMode();
}
}).create().show();
}
});
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
}
private void disableNdefMode() {
Log.d(TAG, "disableNdefMode");
mNfcAdapter.disableForegroundDispatch(this);
mWriteFlag = false;
}
private void enableNdefMode(IntentFilter[] filters) {
Log.d(TAG, "enableNdefMode");
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, filters, null);
mWriteFlag = true;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent");
if (mWriteFlag && (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED) || intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))) {
writeNdef(intent);
Toast.makeText(this, "NDEF への書き込みが完了しました", Toast.LENGTH_LONG).show();
}
}
private void writeNdef(Intent intent) {
Ndef ndef = null;
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage msg = createNdefMessage();
ndef = Ndef.get(tag);
if (ndef != null) {
try {
ndef.connect();
ndef.writeNdefMessage(msg);
ndef.close();
} catch (FormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private NdefMessage createNdefMessage() {
byte[] textBytes = mText.getText().toString().getBytes();
byte[] idBytes = mId.getText().toString().getBytes();
//NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain;charset=utf-8".getBytes(), idBytes, textBytes);
//NdefRecord record = NdefRecord.createMime("text/plain;charset=utf-8", textBytes);
//NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, null, idBytes, textBytes);
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), idBytes, textBytes);
return new NdefMessage(new NdefRecord[] {record});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment