JAVA/android_studio 2024. 6. 29. 15:07

WiFiManagerTest

안드로이드 버젼 7.0 지원하기 위한 버젼임.

 

- MainActivity.java

> OnCreate()에서 BroadcastReceiver 등록

> 퍼미션 요청 , ACCESS_FINE_LOCATION 

> onResume  에서 BroadcastReceiver   등록

> onPause 에서 BroadcastReceiver   해제

public class MainActivity extends AppCompatActivity {
    private WifiManager wifiManager;
    private List<ScanResult> scanDatas; // ScanResult List

    final private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                if (ActivityCompat.checkSelfPermission( context.getApplicationContext() , android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                scanDatas = wifiManager.getScanResults();
                Toast.makeText(context.getApplicationContext(), scanDatas.get(0).SSID, Toast.LENGTH_SHORT).show();
            }else if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                //sendBroadcast(new Intent("wifi.ON_NETWORK_STATE_CHANGED"));  //error
                context.sendBroadcast(new Intent("wifi.ON_NETWORK_STATE_CHANGED"));
            }
        }
    };
    //API Level 30
//    WifiManager.ScanResultsCallback callback = new WifiManager.ScanResultsCallback() {
//        @Override
//        public void onScanResultsAvailable() {
//            // Handle scan results here
//
//        }
//    };
//    Executor executor ;
//    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] PERMS_INITIAL={
                // Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION ,
        };
        ActivityCompat.requestPermissions(this, PERMS_INITIAL, 127);

        Button buttonScan = (Button) findViewById( R.id.btnStartScan) ;
        buttonScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wifiManager.startScan()  ;
                Log.d("WiFiManager" , "startScan() called--")  ;
            }
        });

        //The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N. Try changing `getSystemService` to `getApplicationContext().getSystemService`
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if(!wifiManager.isWifiEnabled()){
            wifiManager.setWifiEnabled(true);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ // N=24, Android7.0 ,
            // Do something for lollipop and above versions
            //{{
            IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) ;
            intentFilter.addAction( WifiManager.NETWORK_STATE_CHANGED_ACTION);
            registerReceiver( receiver , intentFilter) ;
            //}}
        } else{
            // do something for phones running an SDK before lollipop
            Log.d("AndroidVersion" , "Version is below : " + android.os.Build.VERSION.SDK_INT)  ;
        }



    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver( receiver );
    }



}

 

- AndroidManifest.xml

> WiFi연결시 아래의 permission을 추가해줘야 함.

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

 

- build.gradle(:app)

> WiFiManagerTest\app\ 폴더에 있음.

>minSdk,  targetSdk 를 24로 설정후 에러가 없을려면

> dependencies  에서 material의 버젼을 1.5.0으로 설정해야함. 
>>   implementation 'com.google.android.material:material:1.5.0'

plugins {
    id 'com.android.application'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.example.wifimanagertest"
        minSdk 24
        targetSdk 24
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

 

 

posted by cskimair
: