android4.0 WIFI实现网络连接

jopen 11年前

         android4.0上打开wifi后,自动扫描附近所有的wifi热点,连接指定的wifi名称和密码,DHCP动态获取IP后,最后使用Ping命令对连网进行测试。

1.注册wifi的广播接收器:

          监听WifiManager.WIFI_STATE_CHANGED_ACTION消息,并实时处理wifi状态的变化。

    wifi的消息一共有五种:

    WifiManager.WIFI_STATE_DISABLED: //wifi不可用

    WifiManager.WIFI_STATE_DISABLING://wifi 正在关闭或者断开

    WifiManager.WIFI_STATE_ENABLED://wifi可用

    WifiManager.WIFI_STATE_ENABLING://wifi正在打开或者连接

    WifiManager.WIFI_STATE_UNKNOWN://未知消息

    仅在wifi状态为WIFI_STATE_ENABLED的时候,才表示wifi已经连接成功。因此我们在此可以进行连通测试,若想成功获取ip,最好等待3s再去获取ip信息。在测试过程中,发现wifi连网成功后,立马去进行ping命令测试的话,其实际的ip信息还没有来得及设置。

    private void registerWIFI() {          IntentFilter mWifiFilter = new IntentFilter();          mWifiFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);          registerReceiver(mWifiConnectReceiver, mWifiFilter);      }        private BroadcastReceiver mWifiConnectReceiver = new BroadcastReceiver() {     @Override   public void onReceive(Context context, Intent intent) {              Log.d(TAG, "Wifi onReceive action = " + intent.getAction());              if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {                  int message = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);                  Log.d(TAG, "liusl wifi onReceive msg=" + message);    switch (message) {    case WifiManager.WIFI_STATE_DISABLED:        Log.d(TAG, "WIFI_STATE_DISABLED");    break;    case WifiManager.WIFI_STATE_DISABLING:        Log.d(TAG, "WIFI_STATE_DISABLING");    break;    case WifiManager.WIFI_STATE_ENABLED:        Log.d(TAG, "WIFI_STATE_ENABLED");        threadSleep(10000);        pingWifiGateway(EthUtils.getWifiGateWay());    break;    case WifiManager.WIFI_STATE_ENABLING:        Log.d(TAG, "WIFI_STATE_ENABLING");    break;    case WifiManager.WIFI_STATE_UNKNOWN:        Log.d(TAG, "WIFI_STATE_UNKNOWN");    break;    default:                  break;                  }              }          }      };

2.构造一个wifi 的工具类:

    提供打开wifi,关闭wifi,扫描WIFI热点,连接wifi热点,获取IP信息,以及一些wifi热点信息的获取。

import java.util.List;    import android.content.Context;  import android.net.DhcpInfo;  import android.net.wifi.ScanResult;  import android.net.wifi.WifiConfiguration;  import android.net.wifi.WifiInfo;  import android.net.wifi.WifiManager;  import android.net.wifi.WifiManager.WifiLock;  import android.util.Log;    public class WifiAdmin {     private static final String TAG = "[WifiAdmin]";   private WifiManager mWifiManager;   private WifiInfo mWifiInfo;   private List<ScanResult> mWifiList = null;   private List<WifiConfiguration> mWifiConfiguration;   private WifiLock mWifiLock;   private DhcpInfo dhcpInfo;     public WifiAdmin(Context context) {       mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);       mWifiInfo = mWifiManager.getConnectionInfo();   }     public boolean openWifi() {//打开wifi    if (!mWifiManager.isWifiEnabled()) {     Log.i(TAG, "setWifiEnabled.....");     mWifiManager.setWifiEnabled(true);     try {      Thread.sleep(1000);     } catch (InterruptedException e) {      // TODO Auto-generated catch block      e.printStackTrace();     }     Log.i(TAG, "setWifiEnabled.....end");    }    return mWifiManager.isWifiEnabled();   }     public void closeWifi() { if (mWifiManager.isWifiEnabled()) {     mWifiManager.setWifiEnabled(false);    }   }     public int checkState() {    return mWifiManager.getWifiState();   }     public void acquireWifiLock() {//锁定wifiLock    mWifiLock.acquire();   }     public void releaseWifiLock() {//解锁wifiLock    if (mWifiLock.isHeld()) {     mWifiLock.acquire();    }   }     public void creatWifiLock() {    mWifiLock = mWifiManager.createWifiLock("Test");   }     public List<WifiConfiguration> getConfiguration() {    return mWifiConfiguration;   }     public void connectConfiguration(int index) {//指定配置好的网络进行连接    if (index > mWifiConfiguration.size()) {     return;    }    mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);   }     public void startScan() {//wifi扫描    boolean scan = mWifiManager.startScan();    Log.i(TAG, "startScan result:" + scan);    mWifiList = mWifiManager.getScanResults();    mWifiConfiguration = mWifiManager.getConfiguredNetworks();      if (mWifiList != null) {     Log.i(TAG, "startScan result:" + mWifiList.size());     for (int i = 0; i < mWifiList.size(); i++) {      ScanResult result = mWifiList.get(i);      Log.i(TAG, "startScan result[" + i + "]" + result.SSID + "," + result.BSSID);     }     Log.i(TAG, "startScan result end.");    } else {     Log.i(TAG, "startScan result is null.");    }     }     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() + ":");     stringBuilder.append((mWifiList.get(i)).toString());     stringBuilder.append("/n");    }    return stringBuilder;   }     public String getMacAddress() {    return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();   }     public String getBSSID() {    return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();   }     public DhcpInfo getDhcpInfo() {    return dhcpInfo = mWifiManager.getDhcpInfo();   }     public int getIPAddress() {    return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();   }     public int getNetworkId() {    return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();   }     public WifiInfo getWifiInfo() {    mWifiInfo = mWifiManager.getConnectionInfo();    return mWifiInfo;   }     public void addNetwork(WifiConfiguration wcg) { // 添加一个网络配置并连接      int wcgID = mWifiManager.addNetwork(wcg);    boolean b = mWifiManager.enableNetwork(wcgID, true);    System.out.println("addNetwork--" + wcgID);    System.out.println("enableNetwork--" + b);   }     public void disconnectWifi(int netId) {    mWifiManager.disableNetwork(netId);    mWifiManager.disconnect();   }     public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {    Log.i(TAG, "SSID:" + SSID + ",password:" + Password);    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);    } else {     Log.i(TAG, "IsExsits is null.");    }      if (Type == 1) // WIFICIPHER_NOPASS    {     Log.i(TAG, "Type =1.");     config.wepKeys[0] = "";     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);     config.wepTxKeyIndex = 0;    }    if (Type == 2) // WIFICIPHER_WEP    {     Log.i(TAG, "Type =2.");     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    {       Log.i(TAG, "Type =3.");     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) { // 查看以前是否已经配置过该SSID      List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();    for (WifiConfiguration existingConfig : existingConfigs) {     if (existingConfig.SSID.equals("\"" + SSID + "\"")) {      return existingConfig;     }    }    return null;   }  }

3.打开wifi并扫描附近热点:

    wifi打开后,可以通过WifiManager进行wifi热点的扫描。

    EthernetManager mEthManager = null;      WifiManager mWifiManager = null;      connectivityManager mConnectivityManager = null;      WifiAdmin wifiAdmin = null;      mEthManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);      mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);      mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);      wifiAdmin = new WifiAdmin(context);       mEthManager.setEthernetEnabled(false);      boolean open = wifiAdmin.openWifi();      Log.i(TAG, "wifi open:" + open);      wifiAdmin.startScan();      connectWifi();


4.连接指定的wifi名称[SSID]:

    TP-LINK_liusl,密码为:liusl2222

  WIFI的连接类型分为:

        1.没有密码:WIFICIPHER_NOPASS

        2.用wep加密:WIFICIPHER_WEP

        3.用wpa加密:WIFICIPHER_WPA    

    wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(“TP-LINK_liusl”, "liusl2222", 3));

5.获取wifi连接成功后的ip信息:

public static String getWifiGateWay() {        DhcpInfo dhcpInfo = wifiAdmin.getDhcpInfo();      Log.v(" wifi ipAddress", Formatter.formatIpAddress(dhcpInfo.ipAddress) + "");      Log.v("wifi gateway", Formatter.formatIpAddress(dhcpInfo.gateway) + "");      Log.v("wifi dns1", Formatter.formatIpAddress(dhcpInfo.dns1) + "");      Log.v("wifi dns2", Formatter.formatIpAddress(dhcpInfo.dns2) + "");      wifi_gateway = Formatter.formatIpAddress(dhcpInfo.gateway);      return wifi_gateway;  }

6.ping命令测试wifi的连通:

     使用Root权限,通过JNI封装成一个系统库,调用exe command进行ping -c 4 -w 100 192.168.1.1测试。代码将不详细贴出。

    执行结果:

    I/SystemTestingJNI( 1836): executeCommand ret=0, result=PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
    I/SystemTestingJNI( 1836): 64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=6.54 ms
    I/SystemTestingJNI( 1836): 64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.316 ms
    I/SystemTestingJNI( 1836): 64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.194 ms    
    I/SystemTestingJNI( 1836): 64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=0.255 ms
    I/SystemTestingJNI( 1836): 
    I/SystemTestingJNI( 1836): --- 192.168.1.1 ping statistics ---
    I/SystemTestingJNI( 1836): 4 packets transmitted, 4 received, 0% packet loss, time 3001ms
    I/SystemTestingJNI( 1836): rtt min/avg/max/mdev = 0.194/1.826/6.542/2.723 ms

  --还有一种方法,使用Runtime去ping,但是需要注意权限问题,以及输入输出流得自己处理。 exec执行时阻塞、非阻塞,返回结果问题

    Process p= Runtime.getRuntime().exec(cmd);//String cmd

7.添加网络控制权限以及wifi的权限:

    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

来自:http://my.oschina.net/hiliusl/blog/175605