Android 监听wifi总结
功能实现:控制wifi开关,连上某个特定的wifi。
首先先上个wifi工具类,此类转载网上一人,出处不明了。
package rodar.rgs.conference.utils;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;public class WifiConnect { WifiManager wifiManager;
//定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
public enum WifiCipherType
{
WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
}
//构造函数
public WifiConnect(WifiManager wifiManager)
{
this.wifiManager = wifiManager;
}
//打开wifi功能
private boolean OpenWifi()
{
boolean bRet = true;
if (!wifiManager.isWifiEnabled())
{
bRet = wifiManager.setWifiEnabled(true);
}
return bRet;
}
//提供一个外部接口,传入要连接的无线网
public boolean Connect(String SSID, String Password, WifiCipherType Type)
{
if(!this.OpenWifi())
{
return false;
}
System.out.println(">>>wifiCon=");
//开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
//状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING )
{
try{
//为了避免程序一直while循环,让它睡个100毫秒在检测……
Thread.currentThread();
Thread.sleep(100);
}
catch(InterruptedException ie){
}
}
WifiConfiguration wifiConfig = this.CreateWifiInfo(SSID, Password, Type);
//
if(wifiConfig == null)
{
return false;
}
WifiConfiguration tempConfig = this.IsExsits(SSID);
if(tempConfig != null)
{
wifiManager.removeNetwork(tempConfig.networkId);
}
// try {// //高级选项
// String ip ="192.168.1.201";
// int networkPrefixLength =24;
// InetAddress intetAddress = InetAddress.getByName(ip);
// int intIp = inetAddressToInt(intetAddress);
// String dns = (intIp & 0xFF ) + "." + ((intIp >> 8 ) & 0xFF) + "." + ((intIp >> 16 ) & 0xFF) + ".1";
// setIpAssignment("STATIC", wifiConfig); //"STATIC" or "DHCP" for dynamic setting
// setIpAddress(intetAddress, networkPrefixLength, wifiConfig);
// setGateway(InetAddress.getByName(dns), wifiConfig);
// setDNS(InetAddress.getByName(dns), wifiConfig);
// } catch (Exception e) {// // TODO: handle exception
// e.printStackTrace();
// }
int netID = wifiManager.addNetwork(wifiConfig);
boolean bRet = wifiManager.enableNetwork(netID, true);
// wifiManager.updateNetwork(wifiConfig);
return bRet;
}
//查看以前是否也配置过这个网络
private WifiConfiguration IsExsits(String SSID)
{
List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs)
{
if (existingConfig.SSID.equals("\""+SSID+"\""))
{
return existingConfig;
}
}
return null;
}
private WifiConfiguration CreateWifiInfo(String SSID, String Password, WifiCipherType Type)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
if(Type == WifiCipherType.WIFICIPHER_NOPASS)
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if(Type == WifiCipherType.WIFICIPHER_WEP)
{
config.preSharedKey = "\""+Password+"\"";
config.hiddenSSID = true;
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 == WifiCipherType.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;
}
else
{
return null;
}
return config;
}
/***
* Convert a IPv4 address from an InetAddress to an integer
* @param inetAddr is an InetAddress corresponding to the IPv4 address
* @return the IP address as an integer in network byte order
*/
public static int inetAddressToInt(InetAddress inetAddr)
throws IllegalArgumentException {
byte [] addr = inetAddr.getAddress();
if (addr.length != 4) {
throw new IllegalArgumentException("Not an IPv4 address");
}
return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
}
public static void setIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
setEnumField(wifiConf, assign, "ipAssignment");
}
public static void setEnumField(Object obj, String value, String name) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
}
public static void setIpAddress(InetAddress addr, int prefixLength,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, NoSuchMethodException,ClassNotFoundException, InstantiationException,InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class laClass = Class.forName("android.net.LinkAddress");
Constructor laConstructor = laClass.getConstructor(new Class[] {InetAddress.class, int.class });
Object linkAddress = laConstructor.newInstance(addr, prefixLength);
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,"mLinkAddresses");
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
} public static void setGateway(InetAddress gateway,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, ClassNotFoundException,NoSuchMethodException, InstantiationException,InvocationTargetException { Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class routeInfoClass = Class.forName("android.net.RouteInfo");
Constructor routeInfoConstructor = routeInfoClass.getConstructor(new Class[] { InetAddress.class });
Object routeInfo = routeInfoConstructor.newInstance(gateway);
ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,"mRoutes");
mRoutes.clear();
mRoutes.add(routeInfo);
} public static void setDNS(InetAddress dns, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException { Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");
mDnses.clear(); // or add a new dns address , here I just want to replace DNS1
mDnses.add(dns);
}
public static Object getField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
Object out = f.get(obj);
return out;
} public static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
Object out = f.get(obj);
return out;
}
// public void editStaticWifiConfig(final ScanResult sr,String pwd, String ip, String gateway,int prefixLength,String dns) throws Exception{
// WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
//
// if(historyWifiConfig == null){// historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
// int netId = mWifiManager.addNetwork(historyWifiConfig);
// mWifiManager.enableNetwork(netId, true);
// }
//
// setIpAssignment("STATIC", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
// setIpAddress(InetAddress.getByName(ip), prefixLength, historyWifiConfig);
// setGateway(InetAddress.getByName(gateway), historyWifiConfig);
// setDNS(InetAddress.getByName(dns), historyWifiConfig);
//
// mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
// }
//
// public void editDhcpWifiConfig(final ScanResult sr,String pwd) throws Exception{
// WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
//
// if(historyWifiConfig == null){// historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
// int netId = mWifiManager.addNetwork(historyWifiConfig);
// mWifiManager.enableNetwork(netId, true);
// }
//
// setIpAssignment("DHCP", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
//
// mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
// }
}
类中注释高级选项处,是连接上wifi同时自己设定ip.记得wifiManager.updateNetwork(wifiConfig);
类中boolean bRet = wifiManager.enableNetwork(netID, true); 第二个参数true表示如果当前已经有连上一个wifi,要强制连到自己设定的wifi上,此参数必须为true否则连上的还是原来的wifi.
调用此类示例
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiConnect wifi = new WifiConnect(wifiManager); wifi.Connect("wifiName", "wifipPassword", WifiCipherType.WIFICIPHER_WPA);
需要的权限
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
如何在广播监听wifi的状态
广播接收类
package rodar.rgs.conference.utils;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;public class WifiStateReceiver extends BroadcastReceiver{// 0 --> WIFI_STATE_DISABLING
// 1 --> WIFI_STATE_DISABLED
// 2 --> WIFI_STATE_ENABLING
// 3 --> WIFI_STATE_ENABLED
// 4 --> WIFI_STATE_UNKNOWN
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
int oldInt = bundle.getInt("previous_wifi_state");
int newInt = bundle.getInt("wifi_state");
System.out.println(">>>oldInt="+oldInt+",newInt="+newInt);
// String oldStr = (oldInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[oldInt] :"?";
// String newStr = (newInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[newInt] :"?";
// Log.e("", "oldS="+oldStr+", newS="+newStr);
// if(newInt==WifiManager.WIFI_STATE_DISABLED || newInt==WifiManager.WIFI_STATE_ENABLED) {// onWifiStateChange(); // define this function elsewhere!
// } else if(newInt==WifiManager.WIFI_STATE_DISABLING ||
// newInt==WifiManager.WIFI_STATE_ENABLING)
// { chkbox_wifi.setText(newStr);
// } else {// newStr += " (Is wpa_supplicant.conf readable?)";
chkbox_wifi.setText(newStr);
// }
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
System.out.println(">>>onReceive.wifiInfo="+info.toString());
System.out.println(">>>onReceive.SSID="+info.getSSID());
// if(!info.getSSID().equals("Rodar")){// WifiConnect wifi = new WifiConnect(wifiManager);
// wifi.Connect("Rodar", "rodar.5779858",
// WifiCipherType.WIFICIPHER_WPA);
// System.out.println(">>>onReceive.SSID1="+info.getSSID());
// }
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())){Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);if (null != parcelableExtra){NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;switch (networkInfo.getState()){case CONNECTED:Log.e("APActivity", "CONNECTED");break;case CONNECTING:Log.e("APActivity", "CONNECTING");break;case DISCONNECTED:Log.e("APActivity", "DISCONNECTED");break;case DISCONNECTING:Log.e("APActivity", "DISCONNECTING");break;case SUSPENDED:Log.e("APActivity", "SUSPENDED");break;case UNKNOWN:Log.e("APActivity", "UNKNOWN");break;default:break;}}} }
// // 显示Wifi状态以及ip地址:
// public static String StringizeIp(int ip) {// int ip4 = (ip>>24) & 0x000000FF;
// int ip3 = (ip>>16) & 0x000000FF;
// int ip2 = (ip>> 8 )& 0x000000FF;
// int ip1 = ip & 0x000000FF;
// return Integer.toString(ip1) + "." + ip2 + "." + ip3 + "." + ip4;
// }
// private void onWifiStateChange() {// String ip_str = "";
// WifiInfo info = mMainWifi.getConnectionInfo();
// if(info != null) {// int ipaddr = info.getIpAddress();
// ip_str = " (ip="+StringizeIp(ipaddr)+")";
// }
//
// if(mMainWifi.isWifiEnabled()==true)
// chkbox_wifi.setText("Wifi is on [" + ip_str + "]");
// else
// chkbox_wifi.setText("Wifi is off");
//
// }
}
注册和取消广播一般在onstart和onstop里
WifiStateReceiver wifiStateReceiver;
@Override
protected void onStart() {
//注册网络监听
wifiStateReceiver = new WifiStateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiStateReceiver, filter);
super.onStart();
} @Override
protected void onStop() {
//注销网络监听
unregisterReceiver(wifiStateReceiver);
super.onStop();
}
关于广播监控wifi开关还是连接状态可以看这个连接 http://www.cnblogs.com/wanghafan/archive/2013/01/10/2855096.html
Android 监听wifi总结相关推荐
- Android 监听 WiFi 开关状态
Android 监听 WiFi 开关状态 转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/70854309 本文出自[赵彦军的博客] ...
- android 信号强度变化,Android监听WIFI网络的变化并且获得当前信号强度
MainActivity如下: package cc.testwifi; import android.os.Bundle; import android.app.Activity; /** * De ...
- android 监听wifi的连接状态,Android判断wifi状态 监听wifi连接
一.添加权限 二.注册监听广播 注册监听有两种方式 1.AndroidMainfest.xml 中注册 2.在代码中注册 IntentFilter filter = new IntentFilter( ...
- Android监听WIFI信号,这可能是Android上monitore Wifi信号强度的最佳方法
对于那些想知道我是怎么做的人 . 我使用了Job Scheduler,因为它是一个需要 Build wifi连接的任务 . 此外,您可以查看my blog,在那里您可以找到有关此信息和额外信息的更多详 ...
- java wifi监听_Android 监听 WiFi 开关状态
Android 监听 WiFi 开关状态 WifiSwitch_Presenter 源码: package com.yiba.wifi.sdk.lib.presenter; import androi ...
- Android 监听网络连接状态,判断网络连接方式,9.0网络连接,获取已连接WiFi名称SSID和MAC
获取已连接的WiFi名称 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> ...
- android 获取wifi的加密类型,Android WIFI开发:获取wifi列表,连接指定wifi,获取wifi加密方式,监听wifi网络变化等...
下面是 Android 开发中 WiFi 的常用配置,如:获取当前 WiFi ,扫描 WiFi 获取列表,连接指定 WiFi ,监听网络变化等等. 下面是效果图: GitHub 下载地址:https: ...
- android 监听网络状态
今天,讲讲怎么监听手机网络状态的改变. 一.加入网络权限 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:nam ...
- Android监听手机网络变化
Android监听手机网络变化 手机网络状态发生变化会发送广播,利用广播接收者,监听手机网络变化 效果图 注册广播接收者 <?xml version="1.0" encodi ...
最新文章
- s32v 开发板安装 apex 驱动
- 人人都写过的5个Bug!
- 细说SSO单点登录(转)
- CentOS7性能监控系统安装
- LeetCode 10 正则表达式匹配
- duilib学习领悟(4)
- python自动测试相机_Python + Appium+ IOS自动化测试
- SQLServer 分组查询相邻两条记录的时间差
- 车机没有carlife可以自己下载吗_安卓车机CarPlay模块初体验
- 量化投资的现状和前景
- php trim /r/n,「php中trim函数使用」- 海风纷飞Blog
- SpringMVC引入静态org.webjars中资源404
- itsm安装部署(Vmware)
- ValueError: invalid mode: ‘W‘
- tf.name_scope与tf.variable_scope用法区别
- ai是个什么软件,和PS一样么
- python实现从身份证截取出生日期以及性别判断
- 10.6 自注意力和位置编码
- Vert.x(vertx) 创建HTTP服务
- 2D骨骼动画工具Sprite Studio使用教程