今天要说的是通过监听广播的形式连接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
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 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 getScanResultList() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.startScan();
}
return mWifiManager.getScanResults();
}
/**
* 获取已排序后的wifi扫描列表
*
* @return
*/
public List getScanList() {
List 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 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 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.还有一点不要忘记哦,要添加权限滴:
6.好啦,现在我们来测试一下吧
am broadcast -a com.example.mode --es wifi-ssid "wifi名" --es wifi-pwd "wifi密码"
am broadcast -a com.example.mode --es wifi "clear"