티스토리 뷰

Java(자바)안드로이드

[java/android] nfc 태깅하기

개발자 고포고 2024. 2. 21. 15:51
반응형

#안드로이드

#MainActivity

package com.example.myapplication;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
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.TextView;
import androidx.activity.ComponentActivity;
import java.util.Objects;

public class MainActivity extends ComponentActivity {
    private NfcAdapter nfcAdapter;
    private TextView txt;
    private String Tag = "gofogo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        init();
    }

    protected void init() {
        Write("초기화");

        txt = findViewById(R.id.textView);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nfcAdapter == null) {
                    Write("미지원");
                } else {
                    if (nfcAdapter.isEnabled()) {
                        Write("활성화");
                    } else {
                        Write("비활성화");

                    }
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            if (Objects.requireNonNull(intent.getAction()).equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
                parseToText(intent);
            }
        }
    }

    protected void Write(String msg) {
        txt.setText(msg);
        Log.d(Tag, msg);
    }

    protected void parseToText(Intent intent){

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                try {
                    ndef.connect();
                    NdefMessage ndefMessage = ndef.getNdefMessage();
                    if (ndefMessage != null) {
                        NdefRecord[] records = ndefMessage.getRecords();
                        for (NdefRecord ndefRecord : records) {
                            byte[] payload = ndefRecord.getPayload();
                            String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
                            int languageCodeLength = payload[0] & 63;
                            String text = new String(payload, languageCodeLength + 1,
                                    payload.length - languageCodeLength - 1, textEncoding);
                            Write(text);
                            break;
                        }
                    }
                    ndef.close();
                } catch (Exception e) {
                    Write("읽기오류");
                    Log.e(Tag, "읽기 오류", e);
                }
            }
        }


    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        IntentFilter[] filters = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)};
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(this);
    }
}

 

#Java #android #nfc

반응형
댓글
반응형