투케이2K

868. (Android/Java) [유틸 파일] observableReadNfc : NFC 카드 데이터 Tag , NDEF 읽기 - onNewIntent Nfc Read 본문

Android

868. (Android/Java) [유틸 파일] observableReadNfc : NFC 카드 데이터 Tag , NDEF 읽기 - onNewIntent Nfc Read

투케이2K 2024. 9. 6. 13:05

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java / Kotlin

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // TODO [onNewIntent] : [Intent 카드 데이터 Tag , NDEF 읽기 메소드]
    // -----------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {
        c_nfc_card_module.observableReadNfc(intent)
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(new Observer<JSONObject>() { // [Observable.create 타입 지정]
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }
                    @Override
                    public void onNext(@NonNull JSONObject value) {
                        S_Log._W_("observableReadNfc :: NFC Intent Tag , NDEF 확인 수행", new String[]{String.valueOf(value)});
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        S_Log._E_("observableReadNfc :: NFC Intent Tag , NDEF 확인 에러", new String[]{String.valueOf(e.getMessage())});
                    }
                    @Override
                    public void onComplete() {
                    }
                });
    }
    catch (Exception e){
        S_Log._printStackTrace_(null, S_FinalData.LOG_BUG_STATE, null, e);
    }
    */
    // -----------------------------------------------------------------------------------------
    public Observable<JSONObject> observableReadNfc(Intent intent){

        // [로직 처리 실시]
        return Observable.create(subscriber -> {

            try {
                // ===============================================================
                S_Log._D_(ACTIVITY_NAME + " :: NFC 카드 데이터 읽기 수행", null);
                // ===============================================================

                // [팝업창 생성 실시]
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        if (mMainCtx != null && nfcAdapter != null){

                            if (intent != null){

                                // -------------------------------------------------
                                // TODO [NFC 태그 ID 데이터 읽기]
                                // -------------------------------------------------
                                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                                byte[] tagId = null;

                                if (tag != null){
                                    tagId = tag.getId();
                                }
                                // -------------------------------------------------


                                // -------------------------------------------------
                                // TODO [NDEF 메시지 읽기]
                                // -------------------------------------------------
                                Parcelable[] rawMessage = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                                String payloadStr = "";

                                if (rawMessage != null){
                                    NdefMessage[] messages = new NdefMessage[rawMessage.length];

                                    for (int i=0; i<messages.length; i++){
                                        messages[i] = (NdefMessage) rawMessage[i];
                                    }

                                    for (int i=0; i<messages.length; i++){

                                        try {
                                            NdefRecord[] records = messages[i].getRecords();

                                            for(NdefRecord rec : records) {

                                                byte[] payload = rec.getPayload();

                                                String textEncoding = "UTF-8";

                                                if (payload.length > 0) {
                                                    textEncoding = (payload[0] & 0200) == 0 ? "UTF-8" : "UTF-16";
                                                }

                                                // TODO [Get the Language Code]
                                                int languageCodeLength = payload[0] & 0077;
                                                String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

                                                // TODO [Get the Text]
                                                payloadStr = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
                                            }
                                        }
                                        catch (Exception e){}

                                    }
                                }
                                // -------------------------------------------------


                                // -------------------------------------------------
                                // TODO [리턴 JSON 반환]
                                // -------------------------------------------------
                                try {
                                    JSONObject jsonObject = new JSONObject();

                                    // ---------------------------------------------

                                    if (tagId != null && tagId.length > 0){ // TODO [태그 ID]

                                        String hexTagId = C_Encryption.byteToHex(tagId);
                                        hexTagId = hexTagId.replaceAll("0x", "");
                                        hexTagId = hexTagId.replaceAll("0X", "");
                                        hexTagId = hexTagId.replaceAll(" ", "");

                                        jsonObject.put(NFC_HEX_TAG_ID, hexTagId);
                                    }
                                    else {
                                        jsonObject.put(NFC_HEX_TAG_ID, "");
                                    }

                                    // ---------------------------------------------

                                    if (C_Util.stringNotNull(payloadStr) == true){ // TODO [NDEF 메시지]
                                        jsonObject.put(NFC_STRING_NDEF_MSG, payloadStr);
                                    }
                                    else {
                                        jsonObject.put(NFC_STRING_NDEF_MSG, "");
                                    }

                                    // ---------------------------------------------

                                    if (subscriber != null && subscriber.isDisposed() == false){ // TODO [리턴 반환]
                                        subscriber.onNext(jsonObject);
                                        subscriber.onComplete();
                                    }

                                    // ---------------------------------------------

                                }
                                catch (Exception et){
                                    et.printStackTrace();

                                    // TODO [리턴 데이터 반환]
                                    try {
                                        if (subscriber != null && subscriber.isDisposed() == false){
                                            subscriber.onError(new Throwable("[Exception] : " + String.valueOf(et.getMessage())));
                                            subscriber.onComplete();
                                        }
                                    }
                                    catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }

                            }
                            else {

                                // TODO [리턴 데이터 반환]
                                try {
                                    if (subscriber != null && subscriber.isDisposed() == false){
                                        subscriber.onError(new Throwable("[Error] : Intent Is Null"));
                                        subscriber.onComplete();
                                    }
                                }
                                catch (Exception ex){
                                    ex.printStackTrace();
                                }

                            }

                        }
                        else {
                            // TODO [리턴 데이터 반환]
                            try {
                                if (subscriber != null && subscriber.isDisposed() == false){
                                    subscriber.onError(new Throwable("[Error] : Context , nfcAdapter Is Null"));
                                    subscriber.onComplete();
                                }
                            }
                            catch (Exception ex){
                                ex.printStackTrace();
                            }
                        }

                    }
                }, 0);

            } catch (final Exception e){
                S_Log._printStackTrace_(null, S_FinalData.LOG_BUG_STATE, null, e);

                // TODO [리턴 데이터 반환]
                try {
                    if (subscriber != null && subscriber.isDisposed() == false){
                        subscriber.onError(new Throwable("[Exception] : " + String.valueOf(e.getMessage())));
                        subscriber.onComplete();
                    }
                }
                catch (Exception ex){
                    ex.printStackTrace();
                }
            }

        });
    }
 

[결과 출력]

 

        /*
        W  ===================================================================
        [LOG :: CLASS PLACE :: com.example.javaproject.A_Test$2.onNext(A_Test.java:257)]
        ----------------------------------------------------
        [LOG :: NOW TIME :: 2024-09-06 11:10:18 금요일]
        ----------------------------------------------------
        [LOG :: DESCRIPTION :: observableReadNfc :: NFC Intent 확인 수행]
        ----------------------------------------------------
        [LOG :: {"NFC_HEX_TAG_ID":"67eb9ed3","NFC_STRING_NDEF_MSG":"twok"}]
        W  ===================================================================
        // */

 

반응형
Comments