android 10 wifi操作

android 10及以上wifi发生了变化,android 10及以下代码需要适配。

android 10及以上:

1.权限:










2.动态申请位置权限:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
    if(ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }
}

3.android 10以下打开wifi,android 10及以上无法再使用代码打开,需要手动到设置中打开。

/**
 * 打开WIFI(该方法会阻塞线程)
 *
 * @param context
 */
public static void openWifi(Context context) {
    if (Build.VERSION.SDK_INT < 29) {
        WifiManager wifiManager = getWifiManager(context);

        if (!wifiManager.isWifiEnabled()) {
            Log.i(TAG, "wifi is not Enabled");
            boolean isEnabled = wifiManager.setWifiEnabled(true);
            Log.i(TAG, "isEnabled:" + isEnabled);
            // 开启wifi功能需要一段时间,所以要等到wifi
            // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
            while (wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                try {
                    // 为了避免程序一直while循环,让它睡个100毫秒检测……
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                }
            }
        } else {
            Log.i(TAG, "wifi is Enabled");
        }
    } else {
        //Android 10 不支持代码打开WiFi开关,需要用户跳转系统界面自行打开开关
    }
}

4.连接wifi:

public boolean connect(Context context,WifiConfiguration wcg)
{
    final boolean[] isConnected = {false};
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q)
    {
        try {
            NetworkSpecifier specifier =
                    new WifiNetworkSpecifier.Builder()
                            .setSsidPattern(new PatternMatcher(WifiSSID, PatternMatcher.PATTERN_PREFIX))
                            .setWpa2Passphrase(WifiPASSWORD)
                            .build();

            NetworkRequest request =
                    new NetworkRequest.Builder()
                            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                            .setNetworkSpecifier(specifier)
                            .build();

            ConnectivityManager connectivityManager = (ConnectivityManager)
                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

            ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    Log.i(TAG,"WiFi连接成功");
                    System.out.println("wifiInfo=================");
                    isConnected[0] = true;
                }
                @Override
                public void onUnavailable() {
                    Log.i(TAG,"WiFi连接失败,请手动连接");
                }
            };
            //  connectivityManager.registerNetworkCallback(request,networkCallback);
            connectivityManager.requestNetwork(request,networkCallback);
        } catch (SecurityException e){
            e.printStackTrace();
        } catch (IllegalArgumentException e){
            e.printStackTrace();
        } catch (RuntimeException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isConnected[0];
    }else{
        WifiManager wifiManager = getWifiManager(context);
        int wcgID = wifiManager.addNetwork(wcg);
        boolean b = wifiManager.enableNetwork(wcgID, true);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        int count = 0;
        while (true) {
            count++;

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ConnectivityManager conMan = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo.State wifi = conMan.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).getState();
            if (NetworkInfo.State.CONNECTED == wifi) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            }

            if (count > 6000) {
                b = false;
                break;
            }
        }

        System.out.println("connect SSID:" + wcg.SSID);
        System.out.println("connect wcgID:" + wcgID);
        System.out.println("connect enableNetwork:" + b);
        return b;
    }
}

你可能感兴趣的:(android)