android wifi 处理

在android应用程序中可以很方便的使用wifi来处理不同的应用需求,灵活而方面的方法提供给开发者,这里定义了一些常用的wifi处理函数,参考android应用开发解密第八章内容

public class WifiAdmin {
	private String tag = "WifiAdmin";
	private WifiManager wifiManager;
	private WifiInfo wifiInfo;
	private List<ScanResult> wifiList;
	private List<WifiConfiguration> wifiConfiguration;
	WifiLock wifiLock;

	public WifiAdmin(Context context) {
		wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		wifiInfo = wifiManager.getConnectionInfo();
	}
	
	//连接wifi ssid
	public void connected(){
		for(WifiConfiguration config:getConfiguration()){
			String ssid = config.SSID.replace("\"", "");
			if(config.status!=1){
				Log.i(tag, "ssid--------->"+ssid);
				if(ssid.startsWith("OPLK")){
					this.connectConfiguration(config.networkId);
					while (getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
						try {
							Thread.currentThread();
							Thread.sleep(100);
						} catch (InterruptedException ie) {
						}
					}
					break;
				}
			}
		}
	}
	public int getWifiState(){
		return wifiManager.getWifiState();
	}

	//打开wifi
	public void openWifi() {
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
	}

	//关闭wifi
	public void closeWifi() {
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(false);
		}
	}

	//允许一直使用wifi
	public void acquireWifiLock() {
		wifiLock.acquire();
	}

	//释放wifi
	public void releaseWifiLock() {
		if (wifiLock.isHeld()) {
			wifiLock.acquire();
		}
	}

	public void creatWifiLock() {
		wifiLock = wifiManager.createWifiLock("Test");
	}

	public List<WifiConfiguration> getConfiguration() {
		return wifiConfiguration;
	}

	public void connectConfiguration(int networkId) {
		boolean isConn = wifiManager.enableNetwork(networkId, true);
		Log.i(tag, "isConn----->"+isConn);
	}

	public void startScan() {
		wifiManager.startScan();
		wifiList = wifiManager.getScanResults();
		wifiConfiguration = wifiManager.getConfiguredNetworks();
		Log.i(tag, "start scan wifi list size------>"+wifiList.size());
	}

	public List<ScanResult> getWifiList() {
		return wifiList;
	}

	public void LookUpScan() {
		for (ScanResult result:wifiList) {
			Log.i(tag, "wifi ssid---->"+result.SSID);
		}
	}

	public String GetMacAddress() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.getMacAddress();
	}

	public String GetBSSID() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.getBSSID();
	}

	public int GetIPAddress() {
		return (wifiInfo == null) ? 0 : wifiInfo.getIpAddress();
	}

	public int GetNetworkId() {
		return (wifiInfo == null) ? 0 : wifiInfo.getNetworkId();
	}

	public String GetWifiInfo() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.toString();
	}

	public void AddNetwork(WifiConfiguration wcg) {
		int wcgID = wifiManager.addNetwork(wcg);
		wifiManager.enableNetwork(wcgID, true);
	}

	public void DisconnectWifi(int netId) {
		wifiManager.disableNetwork(netId);
		wifiManager.disconnect();
	}
}

 

 

你可能感兴趣的:(android)