Wifi可以自动打开并连接指定的网络(Android)

本文主要介绍通过广播消息监听网络状态的变化,Wifi可以自动打开,而后连接指定的Wifi网络。其中包括屏幕灭屏广播、字符串去除双引号的技术点。亲测可用,收藏发布到此,供大家借鉴学习。

1. 工具类WifiAutoConnectManager

import android.annotation.SuppressLint;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;
import java.util.List;

/**
 * Description:Wifi可以自动打开并连接指定的Wifi网络(工具类)
 */
public class WifiAutoConnectManager {
    private static final String TAG = WifiAutoConnectManager.class.getSimpleName();

    WifiManager wifiManager;

    // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    // 构造函数
    public WifiAutoConnectManager(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    // 提供一个外部接口,传入要连接的无线网
    public void connectWifi(String ssID, String passWord, WifiCipherType type) {
        Log.d(TAG,"connect:" + ssID + ","  + passWord + ","  + type);
        Thread thread = new Thread(new ConnectRunnable(ssID, passWord, type));
        thread.start();
    }

    // 查看以前是否也配置过这个网络
    private WifiConfiguration isExsits(String ssID) {
        Log.d(TAG,"isExsits:" + ssID);

        @SuppressLint("MissingPermission")
        List existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + ssID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    private WifiConfiguration createWifiInfo(String ssID, String passWord, WifiCipherType type) {
        Log.d(TAG,"createWifiInfo:" + ssID + ","  + passWord + ","  + type);
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssID + "\"";

        // NOPASS
        if (type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // WEP
        if (type == WifiCipherType.WIFICIPHER_WEP) {
            if (!TextUtils.isEmpty(passWord)) {
                if (isHexWepKey(passWord)) {
                    config.wepKeys[0] = passWord;
                } else {
                    config.wepKeys[0] = "\"" + passWord + "\"";
                }
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // WPA
        if (type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + passWord + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

            // 此处保证网络自动重联
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    // 打开wifi功能
    private boolean openWifi() {
        boolean isOpen = true;
        if (!wifiManager.isWifiEnabled()) {
            isOpen = wifiManager.setWifiEnabled(true);
            Log.d(TAG,"openWifi");
        }
        return isOpen;
    }

    // 关闭wifi功能
    public void closeWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
            Log.d(TAG,"closeWifi");
        }
    }

    class ConnectRunnable implements Runnable {
        private String ssID;

        private String passWord;

        private WifiCipherType type;

        public ConnectRunnable(String ssID, String passWord, WifiCipherType type) {
            this.ssID = ssID;
            this.passWord = passWord;
            this.type = type;
        }

        @Override
        public void run() {
            // 打开wifi
            openWifi();

            // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
            // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
            while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
                try {
                    // 为了避免程序一直while循环,让它睡个100毫秒检测……
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Log.d(TAG, "Wifi is InterruptedException! " + e.getMessage());
                }
            }

            WifiConfiguration wifiConfig = createWifiInfo(ssID, passWord, type);
            if (wifiConfig == null) {
                Log.d(TAG, "wifiConfig is null!");
                return;
            }

            WifiConfiguration tempConfig = isExsits(ssID);

            if (tempConfig != null) {
                wifiManager.removeNetwork(tempConfig.networkId);
            }

            int netID = wifiManager.addNetwork(wifiConfig);
            boolean enabled = wifiManager.enableNetwork(netID, true);
            Log.d(TAG, "enableNetwork status enable = " + enabled);
            boolean connected = wifiManager.reconnect();
            Log.d(TAG, "enableNetwork connected = " + connected);
        }
    }

    private static boolean isHexWepKey(String wepKey) {
        Log.d(TAG,"isHexWepKey:" + wepKey);

        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        Log.d(TAG,"isHex:" + key);

        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
                return false;
            }
        }

        return true;
    }
}

2. 调用入口:MainActivity

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Description:通过广播消息监听网络状态的变化,连接指定的Wifi网络
 */
public class MainActivity extends AppCompatActivity {
    private String TAG = MainActivity.class.getSimpleName();

    private WifiAutoConnectManager wifiConnector;
    private TextView title, netWorkName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView(){
        Log.d(TAG,"initView");

        title = findViewById(R.id.title);
        netWorkName = findViewById(R.id.netWorkName);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiConnector = new WifiAutoConnectManager(wifiManager);

        //先关闭Wifi,再实现后面的自动重连功能
        wifiManager.setWifiEnabled(false);

        IntentFilter filter = new IntentFilter();
        // 屏幕灭屏广播
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);

        // 监听网络(Wifi)状态变化通知
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(wifiReceiver, filter);
    }

    private BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "action:" + action);

            if (Intent.ACTION_SCREEN_OFF.equals(action)) {     //如果息屏
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                //保持cpu一直运行,不管屏幕是否黑屏
                PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag:CPUKeepRunning");
                wakeLock.acquire();
                Log.d(TAG, "screen off");
            }

            //wifi连接上与否
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {

                    Log.d(TAG, "wifi 已断开");

                    connectWifi();

                    Log.d(TAG, "wifi 重连中");

                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String infoSSID = wifiInfo.getSSID();

                    if (!TextUtils.isEmpty(infoSSID) && infoSSID.length() != 0) {
                        title.setText("已连接上网络:");
                        netWorkName.setVisibility(View.VISIBLE);
                        String netWorkSSID = infoSSID.replace("\"","").replace("\"","");
                        netWorkName.setText(netWorkSSID);

                        //获取当前wifi名称
                        Log.i(TAG, "连接到的网络:" + netWorkSSID);
                        Toast.makeText(MainActivity.this, "已连接上网络:" + netWorkSSID, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    /**
     * 设置: WiFi名称和密码
     */
    private void connectWifi() {
        Log.d(TAG, "connect");
        wifiConnector.connectWifi("MemoryTest", "Auto!1Test#2023#", WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (wifiReceiver != null) {
            unregisterReceiver(wifiReceiver);
        }

        Log.d(TAG,"onDestroy,联网程序被终止");
    }
}

3. 布局:activity_main




    

    

你可能感兴趣的:(用法概括,android,网络,java,Wifi)