1、WifiAdmin类
package com.jack.workticket.remote;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import java.util.List;
/**
* Created by liy on 2017-08-16.
*/
public class WifiAdmin {
// 定义WifiManager对象
private WifiManager mWifiManager;
// 定义WifiInfo对象
private WifiInfo mWifiInfo;
// 扫描出的网络连接列表
private List<ScanResult> mWifiList;
// 网络连接列表
private List<WifiConfiguration> mWifiConfiguration;
// 定义一个WifiLock
WifiManager.WifiLock mWifiLock;
// 构造器
public WifiAdmin(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// 取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
}
//判断wifi是否成功连接
public boolean isWifiConnect(Context context) {
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
// 打开WIFI
public void openWifi() {
if (!mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(true);
}
}
// 关闭WIFI
public void closeWifi() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
}
// 检查当前WIFI状态
public int checkState() {
return mWifiManager.getWifiState();
}
// 锁定WifiLock
public void acquireWifiLock() {
mWifiLock.acquire();
}
// 解锁WifiLock
public void releaseWifiLock() {
// 判断时候锁定
if (mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
// 创建一个WifiLock
public void creatWifiLock() {
mWifiLock = mWifiManager.createWifiLock("Test");
}
// 得到配置好的网络
public List<WifiConfiguration> getConfiguration() {
return mWifiConfiguration;
}
// 指定配置好的网络进行连接
public void connectConfiguration(int index) {
// 索引大于配置好的网络索引返回
if (index > mWifiConfiguration.size()) {
return;
}
// 连接配置好的指定ID的网络
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);
}
public void startScan() {
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
}
// 得到网络列表
public List<ScanResult> getWifiList() {
return mWifiList;
}
// 查看扫描结果
public StringBuilder lookUpScan() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < mWifiList.size(); i++) {
stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
stringBuilder.append((mWifiList.get(i)).toString());
stringBuilder.append("/n");
}
return stringBuilder;
}
// 得到MAC地址
public String getMacAddress() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
}
// 得到接入点的BSSID
public String getBSSID() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
}
// 得到IP地址
public int getIPAddress() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
}
// 得到连接的ID
public int getNetworkId() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
}
// 得到WifiInfo的所有信息包
public String getWifiInfo() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
}
// 添加一个网络并连接
public void addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
boolean b = mWifiManager.enableNetwork(wcgID, true);
Log.v("wcgID_b",wcgID+""+","+b);
}
// 断开指定ID的网络
public void disconnectWifi(int netId) {
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
//然后是一个实际应用方法,只验证过没有密码的情况:
public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type){
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
WifiConfiguration tempConfig = this.IsExsits(SSID);
if(tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
if(Type == 1){ //WIFICIPHER_NOPASS(1、没有密码)
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if(Type == 2){ //WIFICIPHER_WEP(2、wep加密)
config.hiddenSSID = true;
config.wepKeys[0]= "\""+Password+"\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if(Type == 3){ //WIFICIPHER_WPA(3、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;
}
private WifiConfiguration IsExsits(String SSID){
List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
if(!existingConfigs.isEmpty()){
for (WifiConfiguration existingConfig : existingConfigs){
if (existingConfig.SSID.equals("\""+SSID+"\"")){
return existingConfig;
}
}
}
return null;
}
}
2、活动Activity中调用
(1)
/*********************Wifi管理****************************/
public WifiAdminwifiAdmin;
private StringwifiName ="";
private StringwifiPassword ="";
(2)onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("TAG_onCreateLogin", "onCreate()...");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initData();
connectWifi(context);//Wifi管理
}
(3)initData()
private void initData(){
wifiAdmin =new WifiAdmin(this);
wifiAdmin.openWifi();
}
(4)
@Override
protected void onResume() {
connectWifi(context);//Wifi管理
}
(5)
private void connectWifi(){
WifiAdmin wifiAdmin = new WifiAdmin(this);
wifiAdmin.openWifi();//打开wifi
WifiConfiguration wifiConfiguration =wifiAdmin.CreateWifiInfo("jkpms","12345678",3);//配置wifi网络信息
if(wifiConfiguration !=null){
wifiAdmin.addNetwork(wifiConfiguration);//添加配置好的网络并连接
}else{
Toast.makeText(context,"未连接到指定Wifi!",Toast.LENGTH_SHORT).show();
}
}
3、优化connectWifi()
/*************************************Wifi管理**********************************/
private voidconnectWifi(Context context){
if(wifiAdmin.isWifiConnect(context)){
return;
}
wifiName="jkpms";
wifiPassword="12345678";
/*mWifiList = wifiAdmin.getScanWifiList();*/
wifiAdmin.startScan();
mWifiList=wifiAdmin.getWifiList();//未保存网络的Wifi列表(若之前存在保存的网络jkpms则列表为空但会自动连接已保存的网络)
Log.v("wifi_size",mWifiList.size()+"");
if(!mWifiList.isEmpty()){
for(inti=0;i
Log.v("wifi_Name",mWifiList.get(i).SSID);
if(mWifiList.get(i).SSID.equals(wifiName)){
findWifiFlag=true;
break;
}
}
if(findWifiFlag==false){
Toast.makeText(context,"未找到指定Wifi:"+wifiName,Toast.LENGTH_SHORT).show();
}else{
WifiConfiguration wifiConfiguration =wifiAdmin.CreateWifiInfo(wifiName,wifiPassword,3);//配置指定ssid的wifi热点网络信息
if(wifiConfiguration !=null){
wifiAdmin.addNetwork(wifiConfiguration);//添加配置好的网络并连接
}
// try {
// Thread.currentThread().sleep(3000);//阻断3秒
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// if(!wifiAdmin.isWifiConnect(context)){
// Toast.makeText(context,"当前指定Wifi:" + wifiName + "密码错误!", Toast.LENGTH_SHORT).show();
// }
handler.postDelayed(mRunnable,10000);// 在Handler中执行子线程并延迟10s
}
}
}
privateRunnablemRunnable=newRunnable() {
@Override
public voidrun() {
handler.sendEmptyMessage(WIFI_CONNECT_DELAYED);
}
};
public static final intWIFI_CONNECT_DELAYED=6;
finalHandlerhandler=newHandler() {
public voidhandleMessage(Message message) {
switch(message.what) {
caseWIFI_CONNECT_DELAYED://10s后执行代码
if(!wifiAdmin.isWifiConnect(context)){
Toast.makeText(context,"当前指定Wifi:"+wifiName+"密码错误!",Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
super.handleMessage(message);
}
};
3、配置文件manifest
//Wifi控制权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
网友评论