투케이2K

938. (Android/Java) [기능 보완] 안드로이드 15 대응 observableWifiScanList 와이파이 리스트 스캔 수행 본문

Android

938. (Android/Java) [기능 보완] 안드로이드 15 대응 observableWifiScanList 와이파이 리스트 스캔 수행

투케이2K 2025. 1. 15. 20:56

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java / Kotlin

 

[소스 코드]

 

    // ------------------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : observableWifiScanList : 와이파이 리스트 스캔
    // ------------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {

        C_Wifi_Ap_Module.observableWifiScanList(A_Intro.this)
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(new Observer<List<ScanResult>>() { // [Observable.create 타입 지정]
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }
                    @Override
                    public void onNext(@NonNull List<ScanResult> value) {

                    }
                    @Override
                    public void onError(@NonNull Throwable e) {

                    }
                    @Override
                    public void onComplete() {
                    }
                });

    } catch (Exception e) {
        S_Log._printStackTrace_(mContext, S_FinalData.LOG_BUG_STATE, null, e);
    }
    */
    // -----------------------------------------------------------------------------------------
    static String WIFI_M_LOG = "";
    static int WIFI_COUNT = 0;
    static BroadcastReceiver mWifiScanReceiver = null;
    public static Observable<List<ScanResult>> observableWifiScanList(Context mContext) {

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

            // [변수 초기화]
            WIFI_M_LOG = "";
            WIFI_COUNT = 0;

            try {
                // ===============================================================
                S_Log._D_(ACTIVITY_NAME + " :: observableWifiScanList :: 와이파이 리스트 스캔 시작", null);
                // ===============================================================

                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        // [퍼미션 권한 체크 실시]
                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {

                            // [퍼미션이 부여되어있지 않은 경우 종료]
                            WIFI_M_LOG = "[ERROR] : Wifi Scan Permission not Granted (와이파이 스캔에 필요한 권한을 확인해주세요. : GPS , Location)";

                            S_Log._E_(ACTIVITY_NAME + " :: observableWifiScanList :: 에러 발생", new String[]{
                                    "ERROR :: " + String.valueOf(WIFI_M_LOG)
                            });

                            // [리턴 반환 실시]
                            subscriber.onError(new Throwable(WIFI_M_LOG));
                            subscriber.onComplete();

                        } else {

                            // TODO [GPS 권한 부여 상태 체크]
                            if (C_StateCheck.getGpsEnable(mContext) == true){

                                // TODO [Android 15 대응 : 와이파이 활성 상태 체크]
                                if (C_StateCheck.getWifiEnable(mContext) == true){

                                    // ---------------------------------------------------------------
                                    // TODO [와이파이 리스트 스캔 실시]
                                    // ---------------------------------------------------------------
                                    WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                                    wifiManager.startScan();
                                    // List<ScanResult> scanResultList = wifiManager.getScanResults();
                                    // ---------------------------------------------------------------



                                    // ---------------------------------------------------------------
                                    // TODO [핸들러 작업 예약 등록] : [와이파이 리시버 대기]
                                    // ---------------------------------------------------------------

                                    Handler handler = new Handler(Looper.getMainLooper());
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            S_Log._E_(ACTIVITY_NAME + " :: observableWifiScanList :: 와이파이 스캔 에러 발생", new String[]{
                                                    "ERROR :: Wifi Scan Time Out"
                                            });

                                            // [에러 메시지 삽입]
                                            WIFI_M_LOG = "[ERROR] : Wifi Scan Time Out";

                                            // [리턴 반환 실시]
                                            if (subscriber != null && subscriber.isDisposed() == false){

                                                try {
                                                    if (mWifiScanReceiver != null){
                                                        mContext.unregisterReceiver(mWifiScanReceiver);
                                                    }
                                                }
                                                catch (Exception es){
                                                    es.printStackTrace();
                                                }

                                                subscriber.onError(new Throwable(WIFI_M_LOG));
                                                subscriber.onComplete();
                                            }
                                        }

                                    }, WIFI_SCAN_TIMEOUT * 1000);
                                    // ---------------------------------------------------------------



                                    // ---------------------------------------------------------------
                                    // TODO [리시버 설정 실시]
                                    // ---------------------------------------------------------------
                                    mWifiScanReceiver = new BroadcastReceiver() {
                                        @Override
                                        public void onReceive(Context c, Intent intent) {

                                            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                                                // ===============================================================
                                                S_Log._W_(ACTIVITY_NAME + " :: observableWifiScanList :: mWifiScanReceiver onReceive", null);
                                                // ===============================================================

                                                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                                    return;
                                                }

                                                List<ScanResult> scanResultList = wifiManager.getScanResults();

                                                for (ScanResult result : scanResultList) {

                                                    HashMap<String, Object> map = new HashMap<>();
                                                    map.put("SSID", result.SSID); // [SSID]
                                                    map.put("BSSID", result.BSSID); // [BSSID]
                                                    map.put("level", result.level); // [신호 강도]
                                                    map.put("capabilities", result.capabilities); // [암호화 여부]

                                                }


                                                // [중복 데이터 제거]
                                                HashSet hashSet = new HashSet<>(scanResultList);


                                                // [리스트 변환]
                                                List<ScanResult> distinctResultList = new ArrayList<>(hashSet);
                                                WIFI_COUNT = distinctResultList.size();


                                                // [로그 출력]
                                                S_Log._W_(ACTIVITY_NAME + " :: observableWifiScanList :: 와이파이 스캔 완료", new String[]{
                                                        "SCAN COUNT :: " + String.valueOf(WIFI_COUNT),
                                                        "SCAN LIST :: " + String.valueOf(distinctResultList)
                                                });


                                                // ------------------------------------------------------
                                                // TODO [핸들러 예약 작업 취소]
                                                // ------------------------------------------------------
                                                try {
                                                    if (handler != null){
                                                        handler.removeMessages(0);
                                                        handler.removeCallbacks(null);
                                                    }
                                                }
                                                catch (Exception ex){
                                                    ex.printStackTrace();
                                                }


                                                // ------------------------------------------------------
                                                // TODO [리턴 데이터 반환]
                                                // ------------------------------------------------------
                                                try {
                                                    // [메시지 삽입]
                                                    WIFI_M_LOG = "SUCCESS";

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

                                                    // [등록한 리시버 해제]
                                                    mContext.unregisterReceiver(mWifiScanReceiver);
                                                }
                                                catch (Exception ex){
                                                    ex.printStackTrace();
                                                }

                                            }
                                        }
                                    };



                                    // ---------------------------------------------------------------
                                    // TODO [리시버 등록]
                                    // ---------------------------------------------------------------
                                    try {
                                        IntentFilter intentFilter = new IntentFilter();
                                        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
                                        mContext.registerReceiver(mWifiScanReceiver, intentFilter);
                                    }
                                    catch (Exception ez){
                                        ez.printStackTrace();
                                    }
                                    // ---------------------------------------------------------------

                                }
                                else {

                                    // [GPS 권한이 활성화 되어 있지 않은 경우 종료]
                                    WIFI_M_LOG = "[ERROR] : Wifi Enabled False Status";

                                    S_Log._E_(ACTIVITY_NAME + " :: observableWifiScanList :: 에러 발생", new String[]{
                                            "ERROR :: " + String.valueOf(WIFI_M_LOG)
                                    });

                                    // [리턴 반환 실시]
                                    subscriber.onError(new Throwable(WIFI_M_LOG));
                                    subscriber.onComplete();

                                }

                            }
                            else {

                                // [GPS 권한이 활성화 되어 있지 않은 경우 종료]
                                WIFI_M_LOG = "[ERROR] : Wifi Setting Gps Enabled False";

                                S_Log._E_(ACTIVITY_NAME + " :: observableWifiScanList :: 에러 발생", new String[]{
                                        "ERROR :: " + String.valueOf(WIFI_M_LOG)
                                });

                                // [리턴 반환 실시]
                                subscriber.onError(new Throwable(WIFI_M_LOG));
                                subscriber.onComplete();

                            }

                        }

                    }
                }, 0);

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

                // ------------------------------------------------------
                // TODO [리턴 데이터 반환]
                // ------------------------------------------------------
                try {
                    // [에러 메시지 삽입]
                    WIFI_M_LOG = "[EXCEPTION] : " + String.valueOf(e.getMessage());

                    // [리턴 반환 실시]
                    if (subscriber != null && subscriber.isDisposed() == false){
                        subscriber.onError(new Throwable(WIFI_M_LOG));
                        subscriber.onComplete();
                    }
                }
                catch (Exception ex){
                    ex.printStackTrace();
                }
            }

        });
    }

반응형
Comments