Android WIFI的常用操作

一、wifi信息获取

1、打开wifi

public static void openWifi(Context context) {
    WifiManager wifiManager = (WifiManager) ApplicationUtils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        context.startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
    } else {
        if (wifiManager != null) {
            wifiManager.setWifiEnabled(true);
        }
    }
}

2、关闭wifi

public static void closeWifi(Context context) {
    WifiManager wifiManager = (WifiManager) ApplicationUtils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        context.startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
    } else {
        if (wifiManager != null) {
            wifiManager.setWifiEnabled(false);
        }
    }
}

3、wifi是否安全

public static boolean isSecurity(ScanResult scanResult) {
    return !TextUtils.isEmpty(scanResult.capabilities);
}

4、连接指定wifi

/**
 * 连接指定WIFI
 *
 * @param context
 * @param ssid Wi-Fi 设备 SSID
 * @param bssid Wi-Fi 设备 BSSID
 * @param password Wi-Fi 设备密码
 * @param maunal 跳转到系统设置页进行连接
 * @param listener
 */
public static void connectWifi(Context context, String ssid, String bssid, String password, boolean maunal, WifiAutoConnectListener listener) {
    if (listener == null) {
        return;
    }
    WifiManager wifiManager = (WifiManager) ApplicationUtils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        return;
    }
    if (maunal) {
        context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        return;
    }
    WifiInfo connectionInfo = wifiManager.getConnectionInfo();
    if (connectionInfo.getSSID().equals(ssid)) {
        return;
    }
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";
        config.preSharedKey = "\"" + password + "\"";
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        config.status = WifiConfiguration.Status.ENABLED;
        int netId = wifiManager.addNetwork(config);
        boolean b = wifiManager.enableNetwork(netId, true);
        if (b) {
            listener.onSuccess();
        } else {
            listener.onFailure();
        }
    } else {
        WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
                .setSsid(ssid)
                .setBssid(MacAddress.fromString(bssid))
                .setWpa2Passphrase(password)
                .build();

        NetworkRequest request = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(specifier).build();
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                cm.bindProcessToNetwork(network);
                listener.onSuccess();
            }

            @Override
            public void onUnavailable() {
                super.onUnavailable();
                listener.onFailure();
            }
        };
        cm.requestNetwork(request, networkCallback);
    }
}

public interface WifiAutoConnectListener {

    //链接成功
    void onSuccess();
    //链接失败
    void onFailure();
}

5、获取已经连接的wifi信息

public void getConnectedWifi() {
    WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
}

6、获取wifi信息列表

(1)注册wifi列表广播

filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReceiver, filter);

(2)打开wifi

 if (isOpenGPS()) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    MainActivity a = (MainActivity) activity;
    a.startActivityForResult(intent, OPEN_GPS_CODE);
 } else {
    getPermissionWifiList();
 }

(3)请求请问权限

静态注册:

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

动态注册:

private final String[] PERMISSION = {
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_WIFI_STATE
};

ActivityCompat.requestPermissions(MainActivity.this,PERMISSION,PERMISSION_CODE);

权限回调:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    //权限请求成功
    WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    //需要打开GPS,否则scanResults为空
    List<ScanResult> scanResults = wifiManager.getScanResults();
    getWifiListBean.wifiList = new ArrayList<>();
    for (int i = 0; i < scanResults.size(); i++) {
        ScanResult scanResult = scanResults.get(i);
       //路由器的双频段的,2.4G和5G并存,导致扫描出来的两个SSID相同但是BSSID不同的结果
    }
 }

 注意:scanResults为获取到搜索的WIFI信息列表,获取wifi列表必须打开GPS定位,请求权限,否则scanResults为空。

7、当前网络是否是WIFI

public static boolean isWifiConnected() {
    ConnectivityManager connManager = (ConnectivityManager) ApplicationUtils.getContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (null != connManager) {
        NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // wifi
        if (wifi != null) {
            return wifi.isConnected();
        }
    }
    return false;
}

8、当前网络否是移动网络状态

public static boolean isMobileConnected() {
    ConnectivityManager mConnectivityManager = (ConnectivityManager) ApplicationUtils.getContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mobile = mConnectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobile != null) {
        return mobile.isConnected();
    }
    return false;
}

9、当前网络是否畅通

public static boolean isNetworkConnected() {
    ConnectivityManager mConnectivityManager = (ConnectivityManager) ApplicationUtils.getContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    if (mNetworkInfo != null) {
        return mNetworkInfo.isAvailable();
    }
    return false;
}

10、获取当前网络连接的类型信息

public static String getNetworkType() {
    String strNetworkType = "unknown";
    ConnectivityManager manager = (ConnectivityManager) ApplicationUtils.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            strNetworkType = "wifi";
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            strNetworkType = getMobleNet(networkInfo, strNetworkType);
        }
    }
    return strNetworkType;
}

private static String getMobleNet(NetworkInfo networkInfo, String strNetworkType) {
    String strSubTypeName = networkInfo.getSubtypeName();
    int networkType = networkInfo.getSubtype();
    switch (networkType) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_1xRTT:
        case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
            strNetworkType = "2g";
            break;
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_HSDPA:
        case TelephonyManager.NETWORK_TYPE_HSUPA:
        case TelephonyManager.NETWORK_TYPE_HSPA:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
        case TelephonyManager.NETWORK_TYPE_EHRPD:  
        case TelephonyManager.NETWORK_TYPE_HSPAP: 
            strNetworkType = "3g";
            break;
        case TelephonyManager.NETWORK_TYPE_LTE:   
            strNetworkType = "4g";
            break;
        default:
            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                    || strSubTypeName.equalsIgnoreCase("WCDMA")
                    || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                strNetworkType = "3g";
            } else {
                strNetworkType = strSubTypeName;
            }
            break;
    }
    return strNetworkType;
}

二、wifi状态监听

1、注册需要监听的广播

WifiReceiver wifiReceiver = new WifiReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(wifiReceiver, filter));

2、监听广播WifiReceiver

@Override
public void onReceive(Context context, Intent intent) {
    wifiOpenStatus(intent);
    wifiIsConnected(intent);
    wifiOrGprsStatus(intent);
}

3、监听wifi的打开和关闭

private void wifiOpenStatus(Intent intent) {
    if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        int wifiOpenState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
        switch (wifiOpenState) {
            case WifiManager.WIFI_STATE_DISABLED:
                LogUtils.d("wifi已经关闭");
                break;
            case WifiManager.WIFI_STATE_DISABLING:
                LogUtils.d("wifi正在关闭");
                break;
            case WifiManager.WIFI_STATE_ENABLED:
                LogUtils.d("wifi已经打开");
                break;
            case WifiManager.WIFI_STATE_ENABLING:
                LogUtils.d("wifi正在打开");
                break;
            case WifiManager.WIFI_STATE_UNKNOWN:
                LogUtils.d("wifi错误");
                break;
            default:
                break;
        }
    }
}

4、监听wifi是否连上

private void wifiIsConnected(Intent intent) {
    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
            LogUtils.d("wifi断开");
        } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
            WifiManager wifiManager = (WifiManager) ApplicationUtils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            statusListener.wifiSwitchState(NetWorkStatusListener.WIFI_STATE_CONNECTED);
            LogUtils.d("wifi链接上了:" + wifiInfo.getMacAddress());
        }
    }
}

5、wifi和GPRS监听

public void wifiOrGprsStatus(Intent intent) {
    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
        ConnectivityManager manager = (ConnectivityManager) ApplicationUtils.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值