功能实现:控制wifi开关,连上某个特定的wifi。
首先先上个wifi工具类,此类转载网上一人,出处不明了。
package rodar.rgs.conference.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
public class WifiConnect {
WifiManager wifiManager;
//定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
public enum WifiCipherType
{
WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
}
//构造函数
public WifiConnect(WifiManager wifiManager)
{
this.wifiManager = wifiManager;
}
//打开wifi功能
private boolean OpenWifi()
{
boolean bRet = true;
if (!wifiManager.isWifiEnabled())
{
bRet = wifiManager.setWifiEnabled(true);
}
return bRet;
}
//提供一个外部接口,传入要连接的无线网
public boolean Connect(String SSID, String Password, WifiCipherType Type)
{
if(!this.OpenWifi())
{
return false;
}
System.out.println(">>>wifiCon=");
//开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
//状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING )
{
try{
//为了避免程序一直while循环,让它睡个100毫秒在检测……
Thread.currentThread();
Thread.sleep(100);
}
catch(InterruptedException ie){
}
}
WifiConfiguration wifiConfig = this.CreateWifiInfo(SSID, Password, Type);
//
if(wifiConfig == null)
{
return false;
}
WifiConfiguration tempConfig = this.IsExsits(SSID);
if(tempConfig != null)
{
wifiManager.removeNetwork(tempConfig.networkId);
}
// try {
// //高级选项
// String ip ="192.168.1.201";
// int networkPrefixLength =24;
// InetAddress intetAddress = InetAddress.getByName(ip);
// int intIp = inetAddressToInt(intetAddress);
// String dns = (intIp & 0xFF ) + "." + ((intIp >> 8 ) & 0xFF) + "." + ((intIp >> 16 ) & 0xFF) + ".1";
// setIpAssignment("STATIC", wifiConfig); //"STATIC" or "DHCP" for dynamic setting
// setIpAddress(intetAddress, networkPrefixLength, wifiConfig);
// setGateway(InetAddress.getByName(dns), wifiConfig);
// setDNS(InetAddress.getByName(dns), wifiConfig);
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
int netID = wifiManager.addNetwork(wifiConfig);
boolean bRet = wifiManager.enableNetwork(netID, true);
// wifiManager.updateNetwork(wifiConfig);
return bRet;
}
//查看以前是否也配置过这个网络
private WifiConfiguration IsExsits(String SSID)
{
List<WifiConfiguration> 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)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
if(Type == WifiCipherType.WIFICIPHER_NOPASS)
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if(Type == WifiCipherType.WIFICIPHER_WEP)
{
config.preSharedKey = "\""+Password+"\"";
config.hiddenSSID = true;
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 == 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;
}
else
{
return null;
}
return config;
}
/***
* Convert a IPv4 address from an InetAddress to an integer
* @param inetAddr is an InetAddress corresponding to the IPv4 address
* @return the IP address as an integer in network byte order
*/
public static int inetAddressToInt(InetAddress inetAddr)
throws IllegalArgumentException {
byte [] addr = inetAddr.getAddress();
if (addr.length != 4) {
throw new IllegalArgumentException("Not an IPv4 address");
}
return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
}
public static void setIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
setEnumField(wifiConf, assign, "ipAssignment");
}
public static void setEnumField(Object obj, String value, String name) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
}
public static void setIpAddress(InetAddress addr, int prefixLength,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, NoSuchMethodException,ClassNotFoundException, InstantiationException,InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class laClass = Class.forName("android.net.LinkAddress");
Constructor laConstructor = laClass.getConstructor(new Class[] {InetAddress.class, int.class });
Object linkAddress = laConstructor.newInstance(addr, prefixLength);
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,"mLinkAddresses");
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
}
public static void setGateway(InetAddress gateway,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, ClassNotFoundException,NoSuchMethodException, InstantiationException,InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class routeInfoClass = Class.forName("android.net.RouteInfo");
Constructor routeInfoConstructor = routeInfoClass.getConstructor(new Class[] { InetAddress.class });
Object routeInfo = routeInfoConstructor.newInstance(gateway);
ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,"mRoutes");
mRoutes.clear();
mRoutes.add(routeInfo);
}
public static void setDNS(InetAddress dns, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");
mDnses.clear(); // or add a new dns address , here I just want to replace DNS1
mDnses.add(dns);
}
public static Object getField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
Object out = f.get(obj);
return out;
}
public static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
Object out = f.get(obj);
return out;
}
// public void editStaticWifiConfig(final ScanResult sr,String pwd, String ip, String gateway,int prefixLength,String dns) throws Exception{
// WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
//
// if(historyWifiConfig == null){
// historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
// int netId = mWifiManager.addNetwork(historyWifiConfig);
// mWifiManager.enableNetwork(netId, true);
// }
//
// setIpAssignment("STATIC", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
// setIpAddress(InetAddress.getByName(ip), prefixLength, historyWifiConfig);
// setGateway(InetAddress.getByName(gateway), historyWifiConfig);
// setDNS(InetAddress.getByName(dns), historyWifiConfig);
//
// mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
// }
//
// public void editDhcpWifiConfig(final ScanResult sr,String pwd) throws Exception{
// WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
//
// if(historyWifiConfig == null){
// historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
// int netId = mWifiManager.addNetwork(historyWifiConfig);
// mWifiManager.enableNetwork(netId, true);
// }
//
// setIpAssignment("DHCP", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
//
// mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
// }
}
类中注释高级选项处,是连接上wifi同时自己设定ip.记得wifiManager.updateNetwork(wifiConfig);
类中boolean bRet = wifiManager.enableNetwork(netID, true); 第二个参数true表示如果当前已经有连上一个wifi,要强制连到自己设定的wifi上,此参数必须为true否则连上的还是原来的wifi.
调用此类示例
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConnect wifi = new WifiConnect(wifiManager);
wifi.Connect("wifiName", "wifipPassword",
WifiCipherType.WIFICIPHER_WPA);
需要的权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
如何在广播监听wifi的状态
广播接收类
package rodar.rgs.conference.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
public class WifiStateReceiver extends BroadcastReceiver{
// 0 --> WIFI_STATE_DISABLING
// 1 --> WIFI_STATE_DISABLED
// 2 --> WIFI_STATE_ENABLING
// 3 --> WIFI_STATE_ENABLED
// 4 --> WIFI_STATE_UNKNOWN
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
int oldInt = bundle.getInt("previous_wifi_state");
int newInt = bundle.getInt("wifi_state");
System.out.println(">>>oldInt="+oldInt+",newInt="+newInt);
// String oldStr = (oldInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[oldInt] :"?";
// String newStr = (newInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[newInt] :"?";
// Log.e("", "oldS="+oldStr+", newS="+newStr);
// if(newInt==WifiManager.WIFI_STATE_DISABLED || newInt==WifiManager.WIFI_STATE_ENABLED) {
// onWifiStateChange(); // define this function elsewhere!
// } else if(newInt==WifiManager.WIFI_STATE_DISABLING ||
// newInt==WifiManager.WIFI_STATE_ENABLING)
// {
chkbox_wifi.setText(newStr);
// } else {
// newStr += " (Is wpa_supplicant.conf readable?)";
chkbox_wifi.setText(newStr);
// }
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
System.out.println(">>>onReceive.wifiInfo="+info.toString());
System.out.println(">>>onReceive.SSID="+info.getSSID());
// if(!info.getSSID().equals("Rodar")){
// WifiConnect wifi = new WifiConnect(wifiManager);
// wifi.Connect("Rodar", "rodar.5779858",
// WifiCipherType.WIFICIPHER_WPA);
// System.out.println(">>>onReceive.SSID1="+info.getSSID());
// }
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction()))
{
Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (null != parcelableExtra)
{
NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
switch (networkInfo.getState())
{
case CONNECTED:
Log.e("APActivity", "CONNECTED");
break;
case CONNECTING:
Log.e("APActivity", "CONNECTING");
break;
case DISCONNECTED:
Log.e("APActivity", "DISCONNECTED");
break;
case DISCONNECTING:
Log.e("APActivity", "DISCONNECTING");
break;
case SUSPENDED:
Log.e("APActivity", "SUSPENDED");
break;
case UNKNOWN:
Log.e("APActivity", "UNKNOWN");
break;
default:
break;
}
}
}
}
// // 显示Wifi状态以及ip地址:
// public static String StringizeIp(int ip) {
// int ip4 = (ip>>24) & 0x000000FF;
// int ip3 = (ip>>16) & 0x000000FF;
// int ip2 = (ip>> 8 )& 0x000000FF;
// int ip1 = ip & 0x000000FF;
// return Integer.toString(ip1) + "." + ip2 + "." + ip3 + "." + ip4;
// }
// private void onWifiStateChange() {
// String ip_str = "";
// WifiInfo info = mMainWifi.getConnectionInfo();
// if(info != null) {
// int ipaddr = info.getIpAddress();
// ip_str = " (ip="+StringizeIp(ipaddr)+")";
// }
//
// if(mMainWifi.isWifiEnabled()==true)
// chkbox_wifi.setText("Wifi is on [" + ip_str + "]");
// else
// chkbox_wifi.setText("Wifi is off");
//
// }
}
注册和取消广播一般在onstart和onstop里
WifiStateReceiver wifiStateReceiver;
@Override
protected void onStart() {
//注册网络监听
wifiStateReceiver = new WifiStateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiStateReceiver, filter);
super.onStart();
}
@Override
protected void onStop() {
//注销网络监听
unregisterReceiver(wifiStateReceiver);
super.onStop();
}
关于广播监控wifi开关还是连接状态可以看这个连接
http://www.cnblogs.com/wanghafan/archive/2013/01/10/2855096.html