android 10 wifi操作

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

android 10及以上:

1.权限:

复制代码
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

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;
    }
}
相关推荐
weixin_4493108439 分钟前
高效集成:聚水潭采购数据同步到MySQL
android·数据库·mysql
Zender Han1 小时前
Flutter自定义矩形进度条实现详解
android·flutter·ios
白乐天_n3 小时前
adb:Android调试桥
android·adb
姑苏风7 小时前
《Kotlin实战》-附录
android·开发语言·kotlin
数据猎手小k10 小时前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型
你的小1011 小时前
JavaWeb项目-----博客系统
android
风和先行11 小时前
adb 命令查看设备存储占用情况
android·adb
AaVictory.12 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
似霰13 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
大风起兮云飞扬丶13 小时前
Android——网络请求
android