import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log; public class CusWifiUtil { // private static CusWifiUtil mWifiUtils = null;
private List<WifiConfiguration> mWifiConfiguration;
private WifiInfo mWifiInfo;
private DhcpInfo mDhcpInfo;
private List<ScanResult> mWifiList;
private WifiManager.WifiLock mWifiLock;
public WifiManager mWifiManager;
private NetworkInfo mNetworkInfo; private String TAG = "WifiUtils";
private Context mContext; public CusWifiUtil(Context paramContext) {
mContext = paramContext;
mWifiManager = (WifiManager) paramContext
.getSystemService(Context.WIFI_SERVICE);
mDhcpInfo = mWifiManager.getDhcpInfo();
mWifiInfo = mWifiManager.getConnectionInfo();
mNetworkInfo = ((ConnectivityManager) paramContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
} public void setNewWifiManagerInfo() {
mWifiInfo = mWifiManager.getConnectionInfo();
mDhcpInfo = mWifiManager.getDhcpInfo();
} // public static WifiUtils getInstance(Context paramContext) {
// if (mWifiUtils == null)
// mWifiUtils = new WifiUtils(paramContext);
// return mWifiUtils;
// } private WifiConfiguration isExsits(String paramString) {
Iterator<WifiConfiguration> localIterator = mWifiManager
.getConfiguredNetworks().iterator();
WifiConfiguration localWifiConfiguration;
do {
if (!localIterator.hasNext())
return null;
localWifiConfiguration = (WifiConfiguration) localIterator.next();
} while (!localWifiConfiguration.SSID.equals("\"" + paramString + "\""));
return localWifiConfiguration;
} /**
* 获取热点状态
*
* @return boolean值,对应热点的开启(true)和关闭(false)
*/
public boolean getWifiApState() {
try {
int i = ((Integer) mWifiManager.getClass()
.getMethod("getWifiApState", new Class[0])
.invoke(mWifiManager, new Object[0])).intValue();
return (3 == i) || (13 == i);
} catch (Exception localException) {
}
return false;
} /**
* 判断是否连接上wifi
*
* @return boolean值(isConnect),对应已连接(true)和未连接(false)
*/
public boolean isWifiConnect() {
return mNetworkInfo.isConnected();
} public void AcquireWifiLock() {
mWifiLock.acquire();
} public void CreatWifiLock() {
mWifiLock = mWifiManager.createWifiLock("Test");
} // public void OpenWifi() {
// Log.v(TAG, "OpenWifi");
// if (!mWifiManager.isWifiEnabled())
// mWifiManager.setWifiEnabled(true);
// } public void ReleaseWifiLock() {
if (mWifiLock.isHeld())
mWifiLock.release();
} public void closeWifi() {
mWifiManager.setWifiEnabled(false);
} public void connectConfiguration(int paramInt) {
if (paramInt > mWifiConfiguration.size())
return;
mWifiManager
.enableNetwork(
((WifiConfiguration) mWifiConfiguration.get(paramInt)).networkId,
true);
} public void removeNetwork(int netId) {
if (mWifiManager != null) {
mWifiManager.removeNetwork(netId);
}
} public void createWiFiAP(WifiConfiguration paramWifiConfiguration,
boolean paramBoolean) {
try {
Class<? extends WifiManager> localClass = mWifiManager.getClass();
Class[] arrayOfClass = new Class[2];
arrayOfClass[0] = WifiConfiguration.class;
arrayOfClass[1] = Boolean.TYPE;
Method localMethod = localClass.getMethod("setWifiApEnabled",
arrayOfClass);
WifiManager localWifiManager = mWifiManager;
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = paramWifiConfiguration;
arrayOfObject[1] = Boolean.valueOf(paramBoolean);
localMethod.invoke(localWifiManager, arrayOfObject);
return;
} catch (Exception localException) {
localException.printStackTrace();
}
} /**
* 用户创建热点的时候用
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration CreateWifiInfo(String SSID, String Password,
int Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// config.SSID = "\"" + SSID + "\"";
config.SSID = SSID; WifiConfiguration tempConfig = this.IsExsits(SSID);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
} if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
// config.wepKeys[0] = "\"" + Password + "\"";
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
{
// config.preSharedKey = "\"" + Password + "\"";
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;
}
/**
* 用于创建wifi并连接wifi热点,跟CreateWifiInfo差别在于双引号
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration CreateWifiInfoForConnectAP(String SSID, String Password,int Type) {
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);
} if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
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
{
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;
} public void disconnectWifi(int paramInt) {
mWifiManager.disableNetwork(paramInt);
} public String getApSSID() {
try {
Method localMethod = mWifiManager.getClass().getDeclaredMethod(
"getWifiApConfiguration", new Class[0]);
if (localMethod == null)
return null;
Object localObject1 = localMethod.invoke(mWifiManager,
new Object[0]);
if (localObject1 == null)
return null;
WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
if (localWifiConfiguration.SSID != null)
return localWifiConfiguration.SSID;
Field localField1 = WifiConfiguration.class
.getDeclaredField("mWifiApProfile");
if (localField1 == null)
return null;
localField1.setAccessible(true);
Object localObject2 = localField1.get(localWifiConfiguration);
localField1.setAccessible(false);
if (localObject2 == null)
return null;
Field localField2 = localObject2.getClass()
.getDeclaredField("SSID");
localField2.setAccessible(true);
Object localObject3 = localField2.get(localObject2);
if (localObject3 == null)
return null;
localField2.setAccessible(false);
String str = (String) localObject3;
return str;
} catch (Exception localException) {
}
return null;
} public String getBSSID() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getBSSID();
} public String getSSID() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getSSID();
} public List<WifiConfiguration> getConfiguration() {
return mWifiConfiguration;
} public String getLocalIPAddress() {
if (mWifiInfo == null)
return "NULL";
return intToIp(mWifiInfo.getIpAddress());
} public String getServerIPAddress() {
if (mDhcpInfo == null)
return "NULL";
return intToIp(mDhcpInfo.serverAddress);
} public String getMacAddress() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getMacAddress();
} public int getNetworkId() {
if (mWifiInfo == null)
return 0;
return mWifiInfo.getNetworkId();
} public int getWifiApStateInt() {
try {
int i = ((Integer) mWifiManager.getClass()
.getMethod("getWifiApState", new Class[0])
.invoke(mWifiManager, new Object[0])).intValue();
return i;
} catch (Exception localException) {
}
return 4;
} public WifiInfo getWifiInfo() {
return mWifiManager.getConnectionInfo();
} public List<ScanResult> getWifiList() {
return mWifiList;
} public StringBuilder lookUpScan() {
StringBuilder localStringBuilder = new StringBuilder();
for (int i = 0;; i++) {
if (i >= 2)
return localStringBuilder;
localStringBuilder.append("Index_"
+ Integer.valueOf(i + 1).toString() + ":");
localStringBuilder.append(((ScanResult) mWifiList.get(i))
.toString());
localStringBuilder.append("/n");
}
} public void setWifiList() {
mWifiList = mWifiManager.getScanResults();
Log.v(TAG, "mWifiList.size()=" + mWifiList.size());
} public void startScan() {
mWifiManager.startScan();
} public String intToIp(int paramIntip) {
return (paramIntip & 0xFF) + "." + ((paramIntip >> 8) & 0xFF) + "."
+ ((paramIntip >> 16) & 0xFF) + "."
+ ((paramIntip >> 24) & 0xFF);
} /***********************************/
// 打开WIFI
public boolean openWifi() {
mWifiManager = (WifiManager) mContext
.getSystemService(Context.WIFI_SERVICE);
if (!mWifiManager.isWifiEnabled()) {
Log.v(TAG, "打开wifi");
return mWifiManager.setWifiEnabled(true);
}
return true;
} // 添加一个网络并连接
public boolean addNetwork(WifiConfiguration wcg) {
if (!this.openWifi()) {
Log.v("addNetwork", "openWifi is false");
return false;
}
// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
try {
// 为了避免程序一直while循环,让它睡个200毫秒在检测…… Thread.currentThread();
Thread.sleep(200);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
if (wcg == null) {
Log.v("addNetwork", "wcg == null");
return false;
} WifiConfiguration tempConfig = this.IsExsits(wcg.SSID); if (tempConfig != null) {
Log.v("addNetwork", "tempConfig != null");
mWifiManager.removeNetwork(tempConfig.networkId);
} int netID = mWifiManager.addNetwork(wcg);
Log.v("addNetwork", "netID:" + netID);
boolean bRet = mWifiManager.enableNetwork(netID, true);
if (bRet)
Log.v("addNetwork", "enableNetwork:" + bRet);
boolean bConn = mWifiManager.reconnect();
if (bConn)
Log.v("addNetwork", "reconnect:" + bConn);
long startTime = System.currentTimeMillis();
boolean IsConn = false;
while (true) {
mNetworkInfo = ((ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mNetworkInfo.isConnected()) {
IsConn = true;
break;
} else if (System.currentTimeMillis() - startTime > 3 * 1000) {
IsConn = false;
break;
}
}
return IsConn;
} private WifiConfiguration IsExsits(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager
.getConfiguredNetworks();
if (existingConfigs == null)
return null;
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID!=null && existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
/**
* wifi热点开关
*
* @param enabled
* true:打开 false:关闭
* @return true:成功 false:失败
*/
// public boolean setWifiApEnabled(boolean enabled) {
// System.out.println(TAG + ":开启热点");
// if (enabled) { // disable WiFi in any case
// //wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi
// mWifiManager.setWifiEnabled(false);
// System.out.println(TAG + ":关闭wifi");
// }else{
// mWifiManager.setWifiEnabled(true);
// }
// try {
// //热点的配置类
// WifiConfiguration apConfig = new WifiConfiguration();
// //配置热点的名称(可以在名字后面加点随机数什么的)
// apConfig.SSID = WIFI_HOST_SSID;
// //配置热点的密码
// apConfig.preSharedKey = WIFI_HOST_PRESHARED_KEY;
// //安全:WPA2_PSK
// apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
// //通过反射调用设置热点
// Method method = wifiManager.getClass().getMethod(
// "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
// //返回热点打开状态
// return (Boolean) method.invoke(wifiManager, apConfig, enabled);
// } catch (Exception e) {
// return false;
// }
// }
}

注意:CreateWifiInfoForConnectAP 和 CreateWifiInfo的关键区别,使用时注意。不知道为什么创建热点不需要双引号,但是到连接wifi热点时却需要,有知道的童鞋麻烦告知下

android开发 wifi开发工具类的更多相关文章

  1. Android开发调试日志工具类[支持保存到SD卡]

    直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...

  2. wemall app商城源码android开发MD5加密工具类

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享android开发MD5加密工具类主要代码,供 ...

  3. 【移动开发】Android中WIFI开发总结(一)

     WIFI就是一种无线联网技术,常见的是使用无线路由器.那么在这个无线路由器的信号覆盖的范围内都可以采用WIFI连接的方式进行联网.如果无线路由器连接了一个ADSL线路或其他的联网线路,则又被称为“热 ...

  4. 基于JavaMail开发邮件发送器工具类

    基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...

  5. Android开源项目大全 - 工具类

    主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...

  6. 关于TornadoFx和Android的全局配置工具类封装实现及思路解析

    原文地址: 关于TornadoFx和Android的全局配置工具类封装实现及思路解析 - Stars-One的杂货小窝 目前个人开发软件存在设置页面,可以让用户自定义些设置,但我发现,存储数据的代码逻 ...

  7. Android弹出Toast工具类总结

    Android弹出Toast工具类总结,包括系统自带的,也包括自定义的. public class ToastUtil { public ToastUtil() { } public static T ...

  8. Android 中替代 sharedpreferences 工具类的实现

    Android 中替代 sharedpreferences 工具类的实现 背景 想必大家一定用过 sharedpreferences 吧!就我个人而言,特别讨厌每次 put 完数据还要 commit. ...

  9. 获取 Android APP 版本信息工具类(转载)

    获取 Android APP 版本信息工具类 获取手机APP版本信息工具类 1.获取版本名称 2.获取版本号 3.获取App的名称 package com.mingyue.nanshuibeidiao ...

  10. Android 获取手机的厂商、型号、Android系统版本号等工具类(转载)

    Android 获取手机的厂商.型号.Android系统版本号等工具类 1.获取手机制造厂商 2.获取手机型号 3.获取手机系统当前使用的语言 4.获取Android系统版本号 5.获取手机IMEI串 ...

随机推荐

  1. js 实现获取对象所有键名(key)的方法

    1.for in 循环 并且使用hasOwnProperty 方法 var jsonObject1 = { "name": "xiaoming", " ...

  2. 内核linux-3.4.2支持dm9000

    当前烧写:      fs:    nfs 30000000 192.168.1.17:/work/nfs_root/first_fs_mdev.yaffs2    //这里不能使用nfs挂载,只能直 ...

  3. winform 打包部署

    1.使用VS 自带的打包工具,制作winform安装项目 开发环境:VS 2008 Access 操作系统:Windows XP 开发语言:C# 步骤: 第一步:打开开发环境VS2008,新建项目,选 ...

  4. C++ 里 构建动态二维数组

    //****动态二维数组 /* int m=3; int **data; int n=2; data=new int*[m]; for(int j=0;j<m;j++) { data[j]=ne ...

  5. Linux操作系统常用命令

    http://www.cnblogs.com/huangzelin/p/5617611.html http://www.cnblogs.com/liumt/p/6117168.html

  6. 使用RMAN验证备份的有效性

    --验证控制文件和参数文件: RMAN> restore validate controlfile; Starting allocated channel: ORA_DISK_1 channel ...

  7. java的基本数据类型特征

    java的数据类型分为基本数据类型和引用数据类型. 基本数据类型分为数值型.字符型(char).布尔型(boolean) 数值型变量 1.整数型 类型 占用存储空间 表示范围 byte 1字节Byte ...

  8. hdu1007

    Have you ever played quoit in a playground? Quoit is a game in which flat rings are pitched at some ...

  9. 【转】oracle connect by用法

    今天偶然看到connect by,但记不太清楚具体用法了.转了个博客(写的蛮好的),当作笔记. http://www.cnblogs.com/linjiqin/p/3152690.html 先用sco ...

  10. ASP.NET浏览器定义文件及IE兼容模式

    由于ASP.NET4.0中的一个小bug,导致了ASP.NET WebForms控制的CallBack无效,部分控件无法使用. 解决方法是在项目中添加自定义的浏览器定义文件,参考这里:http://w ...