반응형
유니티 C# NFC 태그 리더 읽기 쓰기 사용 방법 간단 구현
NFCManager.cs
using UnityEngine;
public class NFCManager : MonoBehaviour
{
AndroidJavaObject nfcActivity;
void Start()
{
if (Application.platform == RuntimePlatform.Android)
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
nfcActivity = new AndroidJavaObject("com.example.nfcplugin.NFCActivity", activity);
}
}
}
public void EnableNFC()
{
if (nfcActivity != null)
{
nfcActivity.Call("enableNFC");
}
}
public void DisableNFC()
{
if (nfcActivity != null)
{
nfcActivity.Call("disableNFC");
}
}
public void ReadNFC()
{
if (nfcActivity != null)
{
string tagData = nfcActivity.Call<string>("readNFC");
Debug.Log("NFC Tag Data: " + tagData);
}
}
}
Android NFC 기능 구현 (NFCActivity.java)
package com.example.nfcplugin;
import android.app.Activity;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class NFCActivity {
private NfcAdapter nfcAdapter;
private Activity activity;
private String nfcData;
public NFCActivity(Activity unityActivity) {
this.activity = unityActivity;
nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
}
public void enableNFC() {
if (nfcAdapter != null && !nfcAdapter.isEnabled()) {
Toast.makeText(activity, "NFC 활성화 필요", Toast.LENGTH_SHORT).show();
// NFC 설정 창으로 이동
activity.startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
}
}
public void disableNFC() {
// 필요 시 NFC 비활성화 처리
}
public String readNFC() {
// NFC 태그 읽기 처리
Tag detectedTag = activity.getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (detectedTag != null) {
nfcData = bytesToHex(detectedTag.getId());
}
return nfcData;
}
private String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
AndroidManifest 수정
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application>
<activity android:name=".NFCActivity">
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
반응형