android开发 wifi开发工具类
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开发工具类的更多相关文章
- Android开发调试日志工具类[支持保存到SD卡]
直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...
- wemall app商城源码android开发MD5加密工具类
wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享android开发MD5加密工具类主要代码,供 ...
- 【移动开发】Android中WIFI开发总结(一)
WIFI就是一种无线联网技术,常见的是使用无线路由器.那么在这个无线路由器的信号覆盖的范围内都可以采用WIFI连接的方式进行联网.如果无线路由器连接了一个ADSL线路或其他的联网线路,则又被称为“热 ...
- 基于JavaMail开发邮件发送器工具类
基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...
- Android开源项目大全 - 工具类
主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...
- 关于TornadoFx和Android的全局配置工具类封装实现及思路解析
原文地址: 关于TornadoFx和Android的全局配置工具类封装实现及思路解析 - Stars-One的杂货小窝 目前个人开发软件存在设置页面,可以让用户自定义些设置,但我发现,存储数据的代码逻 ...
- Android弹出Toast工具类总结
Android弹出Toast工具类总结,包括系统自带的,也包括自定义的. public class ToastUtil { public ToastUtil() { } public static T ...
- Android 中替代 sharedpreferences 工具类的实现
Android 中替代 sharedpreferences 工具类的实现 背景 想必大家一定用过 sharedpreferences 吧!就我个人而言,特别讨厌每次 put 完数据还要 commit. ...
- 获取 Android APP 版本信息工具类(转载)
获取 Android APP 版本信息工具类 获取手机APP版本信息工具类 1.获取版本名称 2.获取版本号 3.获取App的名称 package com.mingyue.nanshuibeidiao ...
- Android 获取手机的厂商、型号、Android系统版本号等工具类(转载)
Android 获取手机的厂商.型号.Android系统版本号等工具类 1.获取手机制造厂商 2.获取手机型号 3.获取手机系统当前使用的语言 4.获取Android系统版本号 5.获取手机IMEI串 ...
随机推荐
- MongoDb gridfs-ngnix文件存储方案 - 图片
http://www.cnblogs.com/wintersun/p/4622205.html 在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储. ...
- text-rendering 详解
原文链接:http://www.feeldesignstudio.com/2013/05/text-rendering Text-rendering 属性是一个非标准属性,主要用来告诉渲染引擎(ren ...
- CentOS用户权限管理--su与sudo
Linux权限管理--su与sudo 1.su用来切换登录的用户,比如当前用户为chen,可以用su zhu,并输入用户zhu的登录密码,就可以切换到用户zhu.如果一个普通用户想切换到root用户, ...
- excute和query
query(update goods set is_delete=1 where goods_id=13)总是出错??为什么, excute(update goods set is_delete=1 ...
- 主键、外键、超键、候选键的区别【Written By KillerLegend】
先说一下属性的定义: 表的每一行对应一个元组,表的每一列对应一个域.由于域可以相同,为了加以区分,必须对每列起一个唯一的名字,称为属性(Attribute). 再来看看几个键的定义: 超键:在关系模式 ...
- mysql开启全文索引功能
注意:全文检索模块需要mysql开启全文索引功能,开启方法:修改mysql配置文件:window服务器为my.ini,linux服务器为my.cnf,在 [mysqld] 后面加入一行“ft_min_ ...
- .Net异步编程之Async与Await的使用
参考教程:http://www.cnblogs.com/x-xk/archive/2013/06/05/3118005.html http://www.cnblogs.com/tdws/p/56790 ...
- 数据结构学习笔记05图 (邻接矩阵 邻接表-->BFS DFS、最短路径)
数据结构之图 图(Graph) 包含 一组顶点:通常用V (Vertex) 表示顶点集合 一组边:通常用E (Edge) 表示边的集合 边是顶点对:(v, w) ∈E ,其中v, w ∈ V 有向边& ...
- uC/OS-II之系统函数20160526
任务管理 1 OSTaskCreate() 建立一个新任务.任务的建立可以在多任务环境启动之前,也可以在正在运行的任务中建立.中断处理程序中不能 建立任务.一个任务可以为无限循环的结构. 函数原型:I ...
- python基础学习笔记第四天 list 元祖 字典
一 LIST方法 列表操作包含以下函数:1.cmp(list1, list2):比较两个列表的元素 2.len(list):列表元素个数 3.max(list):返回列表元素最大值 4.min(lis ...