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;
    }
}
相关推荐
丘狸尾44 分钟前
[cisco 模拟器] ftp服务器配置
android·运维·服务器
van叶~3 小时前
探索未来编程:仓颉语言的优雅设计与无限可能
android·java·数据库·仓颉
Crossoads7 小时前
【汇编语言】端口 —— 「从端口到时间:一文了解CMOS RAM与汇编指令的交汇」
android·java·汇编·深度学习·网络协议·机器学习·汇编语言
li_liuliu8 小时前
Android4.4 在系统中添加自己的System Service
android
C4rpeDime10 小时前
自建MD5解密平台-续
android
鲤籽鲲12 小时前
C# Random 随机数 全面解析
android·java·c#
m0_5485147715 小时前
2024.12.10——攻防世界Web_php_include
android·前端·php
凤邪摩羯16 小时前
Android-性能优化-03-启动优化-启动耗时
android
凤邪摩羯16 小时前
Android-性能优化-02-内存优化-LeakCanary原理解析
android
喀什酱豆腐16 小时前
Handle
android