通过监听广播的形式连接WiFi

今天要说的是通过监听广播的形式连接WiFi,实现的需求如下所示:


这里写图片描述

好了,现在就让我们实现起来吧
1.Receiver.java

package com.example.mode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author: lijuan
 * @description: wifi连接监听广播器
 * @date: 2017-06-05
 * @time: 15:05
 */
public class Receiver extends BroadcastReceiver {
    public static final String TAG = "Receiver";
    private static final String ACTION = "type";
    private static final String SSID = "wifi-ssid";
    private static final String PWD = "wifi-pwd";
    private static final String WIFI = "wifi";
    public static WifiUtils mWifiUtils;
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.mContext = context;
        mWifiUtils = WifiUtils.getInstance(context);
        final String ssid = intent.getStringExtra(SSID);
        final String pwd = intent.getStringExtra(PWD);
        final String wifi = intent.getStringExtra(WIFI);
        if (!TextUtils.isEmpty(ssid) && !TextUtils.isEmpty(pwd)) {
            connectWifi(ssid, pwd);
        }
        if (!TextUtils.isEmpty(wifi) && wifi.equals("clear")) {
            mWifiUtils.removeExistWiFiConfiguration();
        }
    }

    /**
     * 连接Wifi
     *
     * @param ssid     wifi名
     * @param password wifi密码
     */
    public void connectWifi(final String ssid, final String password) {
        if (!isWifiEnabled()) {
            mWifiUtils.openWifi();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        Log.i(TAG, "已经打开WiFi,现连接WiFi,ssid:" + ssid + ",密码:" + password);
                        mWifiUtils.connectWiFi(ssid, password, 3, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            if (mWifiUtils.getWifiName().equals(ssid)) return;
            Log.i(TAG, "连接WiFi,ssid:" + ssid + ",密码:" + password);
            mWifiUtils.connectWiFi(ssid, password, 3, true);
        }
    }

    /**
     * 判断WIFI是否打开
     */
    public boolean isWifiEnabled() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }
}

2.在AndroidManifest.xml中声明receiver

<receiver android:name=".Receiver">
            <intent-filter>
                <action android:name="com.example.mode" />
            </intent-filter>
        </receiver>

3.好吧,顺便再贴上wifi工具类吧,WifiUtils.java

package com.example.mode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lijuan
 * @description: 对Wifi的操作进行一次封装
 * @date: 2016-12-01
 * @time: 14:44
 */
public class WifiUtils {
    // 上下文
    private Context mContext;
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 排序后的WiFi扫描结果列表
    private List<WifiModel> mWifiModels;
    private final static String CONNECTING = "CONNECTING";
    private final static String CONNECTED = "CONNECTED";
    private final static String DISCONNECTED = "DISCONNECTED";
    // private Timer timer;
    private static final int CONNECT_WIFI_TIMEOUT = 50000; //50秒
    /**
     * 当前正要连接的wifi
     */
    private String ssid;
    /**
     * 当前已经连接上的wifi
     */
    private String wifiName;

    private String TAG = "Wifi";

    private static WifiUtils instance;

    public static WifiUtils getInstance(Context context) {
        if (instance == null) {
            instance = new WifiUtils(context);
        }
        return instance;
    }

    /**
     * 构造器
     *
     * @param context 上下文
     */
    public WifiUtils(Context context) {
        // 初始化WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 初始化WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
        // 初始化WiFi扫描结果列表
        mWifiModels = new ArrayList<>();
        this.mContext = context;
//        this.timer = new Timer();
        startBroadcastReceiver();
    }

    public void unregisterReceiver() {
        try {
            mContext.unregisterReceiver(WiFiStateReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取WiFi结果列表
     *
     * @return
     */
    public List<ScanResult> getScanResultList() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.startScan();
        }
        return mWifiManager.getScanResults();
    }

    /**
     * 获取已排序后的wifi扫描列表
     *
     * @return
     */
    public List<WifiModel> getScanList() {
        List<ScanResult> list = getScanResultList();
        StringBuffer mStringBuffer = new StringBuffer();
        if (list != null) {
            // 每次点击扫描之前清空上一次的扫描结果
            mWifiModels.clear();
            for (int i = 0; i < list.size(); i++) {
                ScanResult mScanResult = list.get(i);
                WifiModel model = new WifiModel(i, mScanResult.SSID, getSignalLevel(mScanResult.level));
                if (!TextUtils.isEmpty(mScanResult.SSID)) mWifiModels.add(model);
                mStringBuffer = mStringBuffer
                        .append(mScanResult.SSID).append("    ")
                        .append(mScanResult.BSSID).append("    ")
                        .append(mScanResult.capabilities).append("    ")
                        .append(mScanResult.frequency).append("    ")
                        .append(mScanResult.level).append("    ")
                        .append("\n");
            }
        }
        // 打印扫描到的wifi列表详情信息
        Log.e(TAG, mStringBuffer.toString());
        Log.e(TAG, "获取wifi列表总共有:" + mWifiModels.size() + "条数据");
        return mWifiModels;
    }

    /**
     * 获取wifi信号强度
     *
     * @param rssi 在RSSI测量的信号的功率
     * @return 0-4 信号为4的时候为最强
     */
    public int getSignalLevel(int rssi) {
        return mWifiManager.calculateSignalLevel(rssi, 5);
    }

    /**
     * 获取当前连接的wifi的信号强度
     *
     * @return 0-4 信号为4的时候为最强
     */
    public int getSignalLevel() {
        return mWifiManager.calculateSignalLevel(mWifiInfo.getRssi(), 5);
    }

    /**
     * 打开WIFI
     */
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭WIFI
     */
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 检查当前WIFI状态
     * 0:WIFI_STATE_DISABLING->wifi正在禁用
     * 1:WIFI_STATE_DISABLED->wifi已禁用
     * 2:WIFI_STATE_ENABLING->wifi正在启用
     * 3:WIFI_STATE_ENABLED->wifi已启用
     * 4:WIFI_STATE_UNKNOWN->wifi为未知
     *
     * @return
     */
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    /**
     * 获取IP地址
     *
     * @return
     */
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    /**
     * 获取连接的ID
     *
     * @return
     */
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    /**
     * 得到MAC地址
     *
     * @return
     */
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    /**
     * 得到接入点的BSSID
     *
     * @return
     */
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    /**
     * 得到WifiInfo的所有信息包
     *
     * @return
     */
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    /**
     * 获取当前已连接的网路名称
     *
     * @return
     */
    public String getWifiName() {
        if (!TextUtils.isEmpty(wifiName)) {
            Log.e(TAG, "当前已经连接的wifi:" + wifiName);
            return wifiName;
        } else {
            return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
        }
    }

    /**
     * 添加一个网络并连接
     *
     * @param wcg
     */
    public void addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        mWifiManager.enableNetwork(wcgID, true);
    }

    /**
     * 断开指定ID的网络
     *
     * @param netId
     */
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    /**
     * 连接wifi
     *
     * @param configuration wifi连接信息
     * @return 本次连接的netWorkId
     */
    public boolean connectWiFi(WifiConfiguration configuration, boolean disableOther) {
        ssid = configuration.SSID.substring(1, configuration.SSID.length() - 2);
        int index = mWifiManager.addNetwork(configuration);
        mWifiManager.saveConfiguration();
        return mWifiManager.enableNetwork(index, disableOther);
    }

    /**
     * 连接wifi
     *
     * @param ssid         ssid
     * @param password     密码
     * @param type         wifi类型
     * @param disableOther 是否其他连接失效
     * @return 本次连接的networkId
     */
    public Boolean connectWiFi(String ssid, String password, int type, boolean disableOther) {
        this.ssid = ssid;
        WifiConfiguration wifi = createWifiConfiguration(ssid, password, type);
        int index = mWifiManager.addNetwork(wifi);
        mWifiManager.saveConfiguration();
        return mWifiManager.enableNetwork(index, disableOther);
    }

    /**
     * 启动监听广播事件,wifi状态
     */
    public void startBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mContext.registerReceiver(WiFiStateReceiver, filter);
    }

    /**
     * wifi状态监听广播器
     */
    private BroadcastReceiver WiFiStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //wifi连接状态发生改变
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                wifiName = info.getExtraInfo().replace("\"", "");
                switch (info.getState().name()) {
                    case CONNECTING:
                        Log.e(TAG, "正在连接:" + wifiName);
                        break;
                    case CONNECTED:
                        if (wifiName.equals("\"" + ssid + "\"")) {
                            Log.e(TAG, "已连接:" + wifiName);
                        } else {
                            Log.e(TAG, "已自动连接:" + wifiName);
                        }
                        break;
                    case DISCONNECTED:
                        if (info.getDetailedState().equals(NetworkInfo.DetailedState.DISCONNECTED) && info.getExtraInfo().equals("\"" + ssid + "\"")) {
                            Log.e(TAG, ssid + "连接失败");
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    };

    /**
     * 创建一个wifi连接信息
     *
     * @param ssid ssid
     * @param pass password
     * @param type 连接类型
     * @return wifi连接信息
     */
    private WifiConfiguration createWifiConfiguration(String ssid, String pass, int type) {
        WifiConfiguration configuration = new WifiConfiguration();
        //清除一些默认wifi的配置
        configuration.allowedAuthAlgorithms.clear();
        configuration.allowedGroupCiphers.clear();
        configuration.allowedKeyManagement.clear();
        configuration.allowedPairwiseCiphers.clear();
        configuration.allowedProtocols.clear();
        configuration.SSID = "\"" + ssid + "\"";
        //清除已存在的相应的ssid
        removeExistWiFiConfiguration(ssid);

        // 分为三种情况:1没有密码2用wep加密3用wpa加密
        switch (type) {
            case 1:       //没有密码
                configuration.wepKeys[0] = "";
                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                configuration.wepTxKeyIndex = 0;
                break;
            case 2:      //wep密码
                configuration.hiddenSSID = true;
                configuration.wepKeys[0] = "\"" + pass + "\"";
                configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                configuration.wepTxKeyIndex = 0;
                break;
            case 3:   //wpa or wpa2 密码
                configuration.preSharedKey = "\"" + pass + "\"";
                configuration.hiddenSSID = true;
                configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                configuration.status = WifiConfiguration.Status.ENABLED;
                break;
        }
        return configuration;
    }

    /**
     * 移除已保存的连接列表中存在的ssid
     *
     * @param ssid ssid
     */
    public void removeExistWiFiConfiguration(String ssid) {
        List<WifiConfiguration> wificonfigList = mWifiManager.getConfiguredNetworks();
        if (wificonfigList == null) return;
        if (wificonfigList.size() < 1) return;
        for (WifiConfiguration wifi : wificonfigList) {
            if (wifi.SSID.equals("\"" + ssid + "\"")) {
                mWifiManager.removeNetwork(wifi.networkId);
                mWifiManager.saveConfiguration();
            }
        }
    }

    /**
     * 移除所有保存在列表的wifi信息
     */
    public void removeExistWiFiConfiguration() {
        List<WifiConfiguration> wificonfigList = mWifiManager.getConfiguredNetworks();
        if (wificonfigList == null) return;
        if (wificonfigList.size() < 1) return;
        for (WifiConfiguration wifi : wificonfigList) {
            mWifiManager.removeNetwork(wifi.networkId);
            mWifiManager.saveConfiguration();
            Log.e(TAG, "删除保存的wifi信息:" + wifi.networkId);
        }
    }
}

4.实体类 WifiModel.java

package com.example.mode;

/**
 * @author: lijuan
 * @description:
 * @date: 2016-12-02
 * @time: 10:11
 */
public class WifiModel {
    private int id;
    private String name;
    private int signalLevel;

    public WifiModel(int id, String name, int signalLevel) {
        this.id = id;
        this.name = name;
        this.signalLevel = signalLevel;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSignalLevel() {
        return signalLevel;
    }

    public void setSignalLevel(int signalLevel) {
        this.signalLevel = signalLevel;
    }
}

5.还有一点不要忘记哦,要添加权限滴:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>

6.好啦,现在我们来测试一下吧

am broadcast -a com.example.mode --es wifi-ssid "wifi名" --es wifi-pwd "wifi密码"
这里写图片描述
am broadcast -a com.example.mode --es wifi "clear"
这里写图片描述
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容