package com.yarin.android.Examples_08_08;
import java.util.List;
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 android.net.wifi.WifiManager.WifiLock;
public class WifiAdmin
{
//定義WifiManager對象
private WifiManager mWifiManager;
//定義WifiInfo對象
private WifiInfo mWifiInfo;
//掃描出的網絡鏈接列表
private List<ScanResult> mWifiList;
//網絡鏈接列表
private List<WifiConfiguration> mWifiConfiguration;
//定義一個WifiLock
WifiLock mWifiLock;
//構造器
public WifiAdmin(Context context)
{
//取得WifiManager對象
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//取得WifiInfo對象
mWifiInfo = mWifiManager.getConnectionInfo();
}
//打開WIFI
public void OpenWifi()
{
if (!mWifiManager.isWifiEnabled())
{
mWifiManager.setWifiEnabled(true);
}
}
//關閉WIFI
public void CloseWifi()
{
if (!mWifiManager.isWifiEnabled())
{
mWifiManager.setWifiEnabled(false);
}
}
//鎖定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);
mWifiManager.enableNetwork(wcgID, true);
}
//斷開指定ID的網絡
public void DisconnectWifi(int netId)
{
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
}