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串 ...
随机推荐
- 比较合并工具vimdiff的主要用法归纳
参考:https://www.ibm.com/developerworks/cn/linux/l-vimdiff/ vimdiff主要用法归纳如下: 1.打开文件 vimdiff file1 fi ...
- leetcode3:不重复的最长子串长度
package hashmap; import java.util.HashMap; import java.util.Map; public class hashmap { public stati ...
- Xen、Openvz、KVM有什么区别?
VPS的全称为Virtual Private Server,叫做虚拟专用服务器(Godaddy称之为Virtual Dedicated Server,VDS).就是利用各种虚拟化手段把单台物理服务器虚 ...
- 安装zabbix
安装zabbix 1. 准备好lamp架构(安装好mysql,php) 2.在数据库中授权: MariaDB [(none)]> create database zabbix charset u ...
- Command
#include <iostream> using namespace std; #define DESTROY_POINTER(ptr) if (ptr) { delete ptr; p ...
- 软件工程 speedsnail 第二次冲刺4
20150521 完成任务:划线第四天,能蜗牛遇到线能反弹,加了障碍物: 遇到问题: 问题1 有一个方向碰到线没有反弹 解决1 没有解决 明日任务: 完善问题1
- Linux搭建NFS提供磁盘给Windows使用
在Windows2008系统下设置挂载Linux服务器磁盘 一.系统环境 系统平台:CentOS release 5.8 (Final) NFS Server IP:X....X...153.157 ...
- JS正则表达式使用方法及示例
1.定义正则表达式: a.普通方式:var reg=/表达式/附加参数 附件参数: g:代表可以进行全局匹配.i:代表不区分大小写匹配.m:代表可以进行多行匹配. 上面三个参数,可以任意组合,代表复合 ...
- C#winform设置DateTimePicker的时间格式
在对DateTimePicker进行时间格式设置时候,要先对属性Format设置为"Custom"自定义格式,然后再CustomFormat里面进行格式设置 比如"yyy ...
- Dynamic Web Project创建及版本修改的问题
java项目中,若切换服务器,经常会涉及到动态web模块版本的问题. 比如:新建了web项目,开始使用tomcat服务器,但是后来使用jboss服务器,就会出现:Project facet ...