文档章节

android4.0 WIFI实现网络连接

_liusl
 _liusl
发布于 2013/11/12 10:24
字数 1234
阅读 12018
收藏 25

         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" />

© 著作权归作者所有

_liusl
粉丝 27
博文 21
码字总数 13790
作品 0
深圳
程序员
私信 提问
Android 支持网络协议以及简单用法

Android对网络编程提供3中接口,即:Java接口,Apache接口,Android接口。Android提供了对HTTP,SSL,Cookie,DHCP等协议的封装,并支持套接字编程,同时对UTI也提供了支持。另外,还提供了连...

Drealin
2012/09/19
956
0
android4.0上实现wifi的wps连接和wps(PIN)连接

Rt,哪位大神指点下如何在android4.0上实现wifi的wps连接和wps(PIN)连接,(目前在4.0上这个功能的接口都处于hide状态,无法直接调用),急求~~

zy_RainBow
2015/11/06
910
0
android4.0 通过DHCP方式实现以太网连接

前段时间做了个厂家测试程序,中间有涉及到网口的检测。基于android4.0的以太网DHCP或者设置静态Ip来实现网络连接,主要实现过程如下: 一。DHCP动态获取ip实现网络连接 1.注册网络状态变化的...

_liusl
2013/11/08
14.5K
15
[资料分享]迅为iTOP4412开发板-SDIO WiFi移植文档

本文转自迅为:http://www.topeetboard.com 概述 近期需要把WiFi无线网络功能移植到iTOP-4412 开发平台,查阅了相关资料,经过一段时间的研究、调试,终于成功的将WiFi功能移植到了开发板上面...

topeet
2015/07/28
244
0
为什么android4.0 setting原码中可以用wifip2pmanager调要enableP2p,自己写的代码里wifiP2pManager却没有这个函数呢?

rt,为什么android4.0 setting原码中可以用wifip2pmanager调要enableP2p,自己写的代码里wifiP2pManager却没有这个函数呢?怎么实现才能可以在自己的代码中启动wifi直连功能呢?...

redtech
2012/11/19
1K
3

没有更多内容

加载失败,请刷新页面

加载更多

正则表达式匹配

请实现一个函数用来匹配包括 '.' 和 '*' 的正则表达式。模式中的字符 '.' 表示任意一个字符,而 '*' 表示它前面的字符可以出现任意次(包含 0 次)。 在本题中,匹配是指字符串的所有字符匹配...

Garphy
59分钟前
6
0
Laravel 5.1的多路由文件的配置

默认的路由配置文件只有一个, \app\Http\routes.php。 在同一个文件中写路由容易起冲突,文件会越来越大,就需要定义多个路由文件。 找到加载\app\Http\routes.php的文件, 打开\app\Provid...

mdoo
今天
5
0
Hibernate 5 开始使用指南前言

同时在面向对象软件和关系型数据库进行工作,可能会非常复杂和费时。数据在对象和数据库之间可能会不一致,然后导致开发成本会非常高。 Hibernate 是一个针对 Java 环境的对象关系映射(Obj...

honeymoose
今天
6
0
聊聊nacos ServiceManager的UpdatedServiceProcessor

序 本文主要研究一下nacos ServiceManager的UpdatedServiceProcessor ServiceManager.init nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java @Compone......

go4it
今天
7
0
正则表达式的使用(QQ格式的判断与空格的切割)

//正则表达式的使用 public static void main(String[] args) throws IOException, ClassNotFoundException { //test1("123456"); test2("-1 99 kk"); } /** * ......

zhengzhixiang
今天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部