Author:Even
WifiManager是管理android WIFI的连接服务,它可以配置WIFI网络连接,管理当前wifi连接,扫描接入点,监视wifi连接状态;
使用必需加权限:
使用getSystemService方法访问
private static WifiManager wifiManager;
String wifiService = getActivity().WIFI_SERVICE;
wifiManager = (WifiManager) getActivity().getSystemService(wifiService);
wifiManager.setWifiEnabled(isChecked);
注册广播:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(receiver, intentFilter);
监听:
/*
* 监听wifi状态
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
Log.i(TAG,"接入点扫描已经完成,从恳求者那里可以得到结果");
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
Log.i(TAG,"获取到wifi开启的广播时,开始扫描");
break;
case WifiManager.WIFI_STATE_DISABLED:
Log.i(TAG,"wifi关闭发出的广播");
break;
}
}else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
/*
* 显示Wi-Fi连接状态改变的广播意图动作
*/
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
Log.i(TAG,"连接已断开");
}
else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
Log.i("AAA","已连接");
} else {
NetworkInfo.DetailedState state = info.getDetailedState();
if (state == state.CONNECTING) {
Log.i("AAA","连接中...");
} else if (state == state.AUTHENTICATING) {
Log.i("AAA","正在验证身份信息...");
} else if (state == state.OBTAINING_IPADDR) {
Log.i("AAA","正在获取IP地址...");
} else if (state == state.FAILED) {
Log.i("AAA","连接失败");
}
}
}
else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { //查看wifi是否在连接状态
if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
Log.i("AAA","查看wifi是否在连接状态 "+false);
} else {
Log.i("AAA","查看wifi是否在连接状态 "+true);
}
}
}
};
我们拿到wifi的状态就可以做很多事了
首先要搜一下wifi信号
/*
* 搜索wifi热点
*/
private void search() {
wifiManager.startScan();
}
存放在list中
List scanResults;
scanResults = wifiManager.getScanResults();
拿到wifi列表它就任你怎么玩了 –
一般而言,你打印就知道,你拿的wifi信号会发现有些是重复的,这是因为把 SSID和BSSI的wifi信号全部扫描出来了,你这个时候,就可以使用这个方法过滤一遍保留ssid
/*
* 以 SSID 为关键字,过滤掉信号弱和重复wifi选项
*/
public static List filterScanResult(final List list) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
LinkedHashMap linkedMap = new LinkedHashMap<>(list.size());
for (ScanResult rst : list) {
if (linkedMap.containsKey(rst.SSID)) {
if (rst.level > linkedMap.get(rst.SSID).level ) {
linkedMap.put(rst.SSID, rst);
}
continue;
}
linkedMap.put(rst.SSID, rst);
}
list.clear();
list.addAll(linkedMap.values());
return list;
}
拿好了wifi列表就可以写一个adapter加载到listview中了
/*
* wifi列表的加载器
*/
public class WifiListAdapter extends ArrayAdapter {
private final LayoutInflater mInflater;
private int mResource;
public WifiListAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(mResource, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.wifi_name);
ScanResult scanResult = getItem(position);
name.setText(scanResult.SSID);
return convertView;
}
}
在加载adapter的时候,可以去获取对应信号的很多信息,包括一些地址,类别,信号强弱,是否需要密码等等
信号强弱
ScanResult scanResult = getItem(position);
int level = scanResult.level;
if (level <= 0 && level >= -50) {
signl.setBackgroundResource(R.drawable.icon_wifi_level4);
} else if (level < -50 && level >= -70) {
signl.setBackgroundResource(R.drawable.icon_wifi_level3);
} else if (level < -70 && level >= -80) {
signl.setBackgroundResource(R.drawable.icon_wifi_level2);
} else if (level < -80 && level >= -100) {
signl.setBackgroundResource(R.drawable.icon_wifi_level1);
}
是否加密
ScanResult scanResult = getItem(position);
String capabilities = scanResult.capabilities;
if (!TextUtils.isEmpty(capabilities)) {
if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
//wpa类型密码
} else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
//wep类型密码
} else {
//无密码
type = WIFICIPHER_NOPASS;
}
}
首先我们要判断指定的wifi信号是否有保存密码
/*
* 判断当前wifi是否有保存
*/
private WifiConfiguration config;
private WifiConfiguration isExsits(String SSID) {
List existingConfigs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
。。。
/*
* 弹出带editText的AlertDialog框,获取输入的密码
*/
if (config == null) {
if (type != WIFICIPHER_NOPASS) {//需要密码
final EditText editText = new EditText(getActivity());
final int finalType = type;
new AlertDialog.Builder(getActivity()).setTitle(
getResources().getString(R.string.enter_wifi)).setIcon(
android.R.drawable.ic_dialog_info).setView(
editText).setPositiveButton(
getResources().getString(R.string.confirm),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
config = createWifiInfo(scanResult.SSID, editText.getText().toString(), finalType);
connect(config,position);
}
})
.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
return;
} else {
config = createWifiInfo(scanResult.SSID, "", type);
connect(config,position);
}
。。。
/*
* 连接的方法
*/
private int wcgID;
private void connect(WifiConfiguration config,int position) {
Visible_cur_wifi_view(true);
wcgID = wifiManager.addNetwork(config);
wifiManager.enableNetwork(wcgID, true);
}
/*
* 传入对应的wifi的ssid
忘却密码的方法
*/
public void removeWifi_si(String charSequence){
List wifiConfigurations = wifiManager.getConfiguredNetworks();
//忘却wifi密码
for (WifiConfiguration wifiConfig : wifiConfigurations) {
String ssid = wifiConfig.SSID;
if (ssid.substring(1, ssid.length() - 1).equals(charSequence)) {
wifiManager.removeNetwork(wifiConfig.networkId);
wifiManager.saveConfiguration();
}
}
}
wifiManager.disconnect();