Android WiFi开发 (二)Wifi热点

标签: wi-fiandroid热点安全
2016-03-07 13:08  11415人阅读  评论(29)  收藏  举报
  分类:
Android 基础(21) 

版权声明:本文出自张朋永的博客,转载必须注明出处。

目录(?)[+]

接着上一篇wifi的扫描连接等,这一篇主要说一下手机开启Wifi热点。

demo的下载地址会在最下面贴出来。

图片:

       

1 创建WIFI热点

经测试开启wifi热点(无秘密,wpa安全类型,wpa2安全类型)都可以正常开启并使用。

需要注意的是wifi和wifi热点不能同时打开,也就是连接wifi的时候,开启热点需要先将wifi关闭才可以。

用到的主要代码:

[java]  view plain copy print ?
  1. package com.vn.wifitest.utils;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import android.content.BroadcastReceiver;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.IntentFilter;
  8. import android.net.wifi.WifiConfiguration;
  9. import android.net.wifi.WifiConfiguration.KeyMgmt;
  10. import android.net.wifi.WifiManager;
  11. import android.os.Handler;
  12. import android.util.Log;
  13. public class WifiAPUtil {
  14. private static final String TAG = "WifiAPUtil";
  15. public final static boolean DEBUG = true;
  16. public static final int MESSAGE_AP_STATE_ENABLED = 1;
  17. public static final int MESSAGE_AP_STATE_FAILED = 2;
  18. //默认wifi秘密
  19. private static final String DEFAULT_AP_PASSWORD = "12345678";
  20. private static WifiAPUtil sInstance;
  21. private static Handler mHandler;
  22. private static Context mContext;
  23. private WifiManager mWifiManager;
  24. //监听wifi热点的状态变化
  25. public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED";
  26. public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
  27. public static int WIFI_AP_STATE_DISABLING = 10;
  28. public static int WIFI_AP_STATE_DISABLED = 11;
  29. public static int WIFI_AP_STATE_ENABLING = 12;
  30. public static int WIFI_AP_STATE_ENABLED = 13;
  31. public static int WIFI_AP_STATE_FAILED = 14;
  32. public enum WifiSecurityType {
  33. WIFICIPHER_NOPASS, WIFICIPHER_WPA, WIFICIPHER_WEP, WIFICIPHER_INVALID, WIFICIPHER_WPA2
  34. }
  35. private WifiAPUtil(Context context) {
  36. if(DEBUG) Log.d(TAG,"WifiAPUtils construct");
  37. mContext = context;
  38. mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  39. IntentFilter filter = new IntentFilter();
  40. filter.addAction(WIFI_AP_STATE_CHANGED_ACTION);
  41. context.registerReceiver(mWifiStateBroadcastReceiver, filter);
  42. }
  43. protected void finalize() {
  44. if(DEBUG) Log.d(TAG,"finalize");
  45. mContext.unregisterReceiver(mWifiStateBroadcastReceiver);
  46. }
  47. public static WifiAPUtil getInstance(Context c) {
  48. if (null == sInstance)
  49. sInstance = new WifiAPUtil(c);
  50. return sInstance;
  51. }
  52. public boolean turnOnWifiAp(String str, String password,WifiSecurityType Type) {
  53. String ssid = str;
  54. //配置热点信息。
  55. WifiConfiguration wcfg = new WifiConfiguration();
  56. wcfg.SSID = new String(ssid);
  57. wcfg.networkId = 1;
  58. wcfg.allowedAuthAlgorithms.clear();
  59. wcfg.allowedGroupCiphers.clear();
  60. wcfg.allowedKeyManagement.clear();
  61. wcfg.allowedPairwiseCiphers.clear();
  62. wcfg.allowedProtocols.clear();
  63. if(Type == WifiSecurityType.WIFICIPHER_NOPASS) {
  64. if(DEBUG)Log.d(TAG, "wifi ap----no password");
  65. wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN, true);
  66. wcfg.wepKeys[0] = "";
  67. wcfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
  68. wcfg.wepTxKeyIndex = 0;
  69. } else if(Type == WifiSecurityType.WIFICIPHER_WPA) {
  70. if(DEBUG)Log.d(TAG, "wifi ap----wpa");
  71. //密码至少8位,否则使用默认密码
  72. if(null != password && password.length() >= 8){
  73. wcfg.preSharedKey = password;
  74. } else {
  75. wcfg.preSharedKey = DEFAULT_AP_PASSWORD;
  76. }
  77. wcfg.hiddenSSID = false;
  78. wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
  79. wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
  80. wcfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
  81. //wcfg.allowedKeyManagement.set(4);
  82. wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
  83. wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
  84. wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
  85. wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
  86. } else if(Type == WifiSecurityType.WIFICIPHER_WPA2) {
  87. if(DEBUG)Log.d(TAG, "wifi ap---- wpa2");
  88. //密码至少8位,否则使用默认密码
  89. if(null != password && password.length() >= 8){
  90. wcfg.preSharedKey = password;
  91. } else {
  92. wcfg.preSharedKey = DEFAULT_AP_PASSWORD;
  93. }
  94. wcfg.hiddenSSID = true;
  95. wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
  96. wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
  97. wcfg.allowedKeyManagement.set(4);
  98. //wcfg.allowedKeyManagement.set(4);
  99. wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
  100. wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
  101. wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
  102. wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
  103. }
  104. try {
  105. Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration",
  106. wcfg.getClass());
  107. Boolean rt = (Boolean)method.invoke(mWifiManager, wcfg);
  108. if(DEBUG) Log.d(TAG, " rt = " + rt);
  109. } catch (NoSuchMethodException e) {
  110. Log.e(TAG, e.getMessage());
  111. } catch (IllegalArgumentException e) {
  112. Log.e(TAG, e.getMessage());
  113. } catch (IllegalAccessException e) {
  114. Log.e(TAG, e.getMessage());
  115. } catch (InvocationTargetException e) {
  116. Log.e(TAG, e.getMessage());
  117. }
  118. return setWifiApEnabled();
  119. }
  120. //获取热点状态
  121. public int getWifiAPState() {
  122. int state = -1;
  123. try {
  124. Method method2 = mWifiManager.getClass().getMethod("getWifiApState");
  125. state = (Integer) method2.invoke(mWifiManager);
  126. } catch (Exception e) {
  127. Log.e(TAG, e.getMessage());
  128. }
  129. if(DEBUG)Log.i("WifiAP", "getWifiAPState.state " + state);
  130. return state;
  131. }
  132. private boolean setWifiApEnabled() {
  133. //开启wifi热点需要关闭wifi
  134. while(mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED){
  135. mWifiManager.setWifiEnabled(false);
  136. try {
  137. Thread.sleep(200);
  138. } catch (Exception e) {
  139. Log.e(TAG, e.getMessage());
  140. return false;
  141. }
  142. }
  143. // 确保wifi 热点关闭。
  144. while(getWifiAPState() != WIFI_AP_STATE_DISABLED){
  145. try {
  146. Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
  147. WifiConfiguration.class, boolean.class);
  148. method1.invoke(mWifiManager, null, false);
  149. Thread.sleep(200);
  150. } catch (Exception e) {
  151. Log.e(TAG, e.getMessage());
  152. return false;
  153. }
  154. }
  155. //开启wifi热点
  156. try {
  157. Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
  158. WifiConfiguration.class, boolean.class);
  159. method1.invoke(mWifiManager, null, true);
  160. Thread.sleep(200);
  161. } catch (Exception e) {
  162. Log.e(TAG, e.getMessage());
  163. return false;
  164. }
  165. return true;
  166. }
  167. //关闭WiFi热点
  168. public void closeWifiAp() {
  169. if (getWifiAPState() != WIFI_AP_STATE_DISABLED) {
  170. try {
  171. Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
  172. method.setAccessible(true);
  173. WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
  174. Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
  175. method2.invoke(mWifiManager, config, false);
  176. } catch (NoSuchMethodException e) {
  177. e.printStackTrace();
  178. } catch (IllegalArgumentException e) {
  179. e.printStackTrace();
  180. } catch (IllegalAccessException e) {
  181. e.printStackTrace();
  182. } catch (InvocationTargetException e) {
  183. e.printStackTrace();
  184. }
  185. }
  186. }
  187. public void regitsterHandler(Handler handler){
  188. mHandler = handler;
  189. }
  190. public void unregitsterHandler(){
  191. mHandler = null;
  192. }
  193. //监听wifi热点状态变化
  194. private BroadcastReceiver mWifiStateBroadcastReceiver = new BroadcastReceiver() {
  195. @Override
  196. public void onReceive(Context context, Intent intent) {
  197. if(DEBUG)Log.i(TAG,"WifiAPUtils onReceive: "+intent.getAction());
  198. if(WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) {
  199. int cstate = intent.getIntExtra(EXTRA_WIFI_AP_STATE, -1);
  200. if(cstate == WIFI_AP_STATE_ENABLED) {
  201. if(mHandler != null){
  202. mHandler.sendEmptyMessage(MESSAGE_AP_STATE_ENABLED);
  203. }
  204. }if(cstate == WIFI_AP_STATE_DISABLED  || cstate == WIFI_AP_STATE_FAILED) {
  205. if(mHandler != null)
  206. mHandler.sendEmptyMessage(MESSAGE_AP_STATE_FAILED);
  207. }
  208. }
  209. }
  210. };
  211. //获取热点ssid
  212. public String getValidApSsid() {
  213. try {
  214. Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
  215. WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager);
  216. return configuration.SSID;
  217. } catch (Exception e) {
  218. Log.e(TAG, e.getMessage());
  219. return null;
  220. }
  221. }
  222. //获取热点密码
  223. public String getValidPassword(){
  224. try {
  225. Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
  226. WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager);
  227. return configuration.preSharedKey;
  228. } catch (Exception e) {
  229. Log.e(TAG, e.getMessage());
  230. return null;
  231. }
  232. }
  233. //获取热点安全类型
  234. public int getValidSecurity(){
  235. WifiConfiguration configuration;
  236. try {
  237. Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
  238. configuration = (WifiConfiguration)method.invoke(mWifiManager);
  239. } catch (Exception e) {
  240. Log.e(TAG, e.getMessage());
  241. return WifiSecurityType.WIFICIPHER_INVALID.ordinal();
  242. }
  243. if(DEBUG)Log.i(TAG,"getSecurity security="+configuration.allowedKeyManagement);
  244. if(configuration.allowedKeyManagement.get(KeyMgmt.NONE)) {
  245. return WifiSecurityType.WIFICIPHER_NOPASS.ordinal();
  246. }else if(configuration.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
  247. return WifiSecurityType.WIFICIPHER_WPA.ordinal();
  248. }else if(configuration.allowedKeyManagement.get(4)) { //4 means WPA2_PSK
  249. return WifiSecurityType.WIFICIPHER_WPA2.ordinal();
  250. }
  251. return WifiSecurityType.WIFICIPHER_INVALID.ordinal();
  252. }
  253. }

使用方法:

Activity生命周期中

[java]  view plain copy print ?
  1. //初始化WifiAPUtil类
  2. WifiAPUtil.getInstance(getApplicationContext())
  3. //注册handler
  4. WifiAPUtil.getInstance(this).regitsterHandler(mHandler);
  5. //接收message,做处理
  6. private Handler mHandler = new Handler(){
  7. public void handleMessage(Message msg) {
  8. switch (msg.what) {
  9. case WifiAPUtil.MESSAGE_AP_STATE_ENABLED:
  10. String ssid = WifiAPUtil.getInstance(WifiApActivity.this).getValidApSsid();
  11. String pw = WifiAPUtil.getInstance(WifiApActivity.this).getValidPassword();
  12. int security = WifiAPUtil.getInstance(WifiApActivity.this).getValidSecurity();
  13. mWifiApState.setText("wifi热点开启成功"+"\n"
  14. +"SSID = "+ssid+"\n"
  15. +"Password = "+pw +"\n"
  16. +"Security = "+security);
  17. break;
  18. case WifiAPUtil.MESSAGE_AP_STATE_FAILED:
  19. mWifiApState.setText("wifi热点关闭");
  20. break;
  21. default:
  22. break;
  23. }
  24. }
  25. };

在activity销毁的时候

[java]  view plain copy print ?
  1. @Override
  2. protected void onDestroy() {
  3. super.onDestroy();
  4. WifiAPUtil.getInstance(this).unregitsterHandler();
  5. }

添加点击事件

[java]  view plain copy print ?
  1. //开启wifi热点
  2. WifiAPUtil.getInstance(WifiApActivity.this).turnOnWifiAp(ssid, password, mWifiType);
[java]  view plain copy print ?
  1. //关闭wifi热点
  2. WifiAPUtil.getInstance(WifiApActivity.this).closeWifiAp();

2 监听热点的状态

当wifi热点状态发送变化,系统会发送广播 Android.net.wifi.WIFI_AP_STATE_CHANGED,所以我们只要注册监听这个广播就可以了。

wifi ap状态值。

[java]  view plain copy print ?
  1. public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
  2. public static int WIFI_AP_STATE_DISABLING = 10;
  3. public static int WIFI_AP_STATE_DISABLED = 11;
  4. public static int WIFI_AP_STATE_ENABLING = 12;
  5. public static int WIFI_AP_STATE_ENABLED = 13;
  6. public static int WIFI_AP_STATE_FAILED = 14;

动态注册

[java]  view plain copy print ?
  1. public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED";
  2. //注册广播接收者
  3. IntentFilter filter = new IntentFilter();
  4. filter.addAction(WIFI_AP_STATE_CHANGED_ACTION);
  5. context.registerReceiver(mWifiStateBroadcastReceiver, filter);

广播接收者

通过监听wifiap状态的变化,发送消息给相关activity

[java]  view plain copy print ?
  1. //监听wifi热点状态变化
  2. private BroadcastReceiver mWifiStateBroadcastReceiver = new BroadcastReceiver() {
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5. if(DEBUG)Log.i(TAG,"WifiAPUtils onReceive: "+intent.getAction());
  6. if(WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) {
  7. int cstate = intent.getIntExtra(EXTRA_WIFI_AP_STATE, -1);
  8. if(cstate == WIFI_AP_STATE_ENABLED) {
  9. if(mHandler != null){
  10. mHandler.sendEmptyMessage(MESSAGE_AP_STATE_ENABLED);
  11. }
  12. }if(cstate == WIFI_AP_STATE_DISABLED  || cstate == WIFI_AP_STATE_FAILED) {
  13. if(mHandler != null)
  14. mHandler.sendEmptyMessage(MESSAGE_AP_STATE_FAILED);
  15. }
  16. }
  17. }
  18. };

3 遗留问题

在配置wificonfiguration的时候有过属性是hiddenSSID,这个是设置wifi热点AP是否隐藏的,

但是设置wcfg.hiddenSSID = true或false并没有发现有什么不同,按理说设置为true,ssid隐藏应该搜索不到这个热点,

但是都可以搜索到。还请知道的可以留言指教,十分感谢。

之前有朋友说5.0系统的开启热点有问题,我这里没有5.0的手机,使用华为p9Android6.0手机测试确实开启不了热点,需要添加write_settings,添加上此权限就可以成功开启了。

DEMO下载

Android WiFi开发 (二)分享Wifi热点相关推荐

  1. 【 Android11 WiFi开发 二 】WiFi连接、断开

    前言 上篇文章介绍了WiFi列表的获取与展示和WiFi状态改变的广播监听,本篇将介绍介绍对WiFi的操作,连接.忘记,查看已连接的WiFi信息等. 相关文章 1.[ Android11 WiFi开发 ...

  2. 【Android游戏开发二十七】讲解游戏开发与项目下的hdpi 、mdpi与ldpi资源文件夹以及游戏高清版本的设置...

    今天一个开发者问到我为什么游戏开发要删除项目下的hdpi.mdpi和ldpi文件夹:下面详细给大家解答一下: 首先童鞋们如果看过我写的<[Android游戏开发二十一]Android os设备谎 ...

  3. Android画板开发(二) 橡皮擦实现

    Android画板开发(一) 基本画笔的实现 Android画板开发(二) 橡皮擦实现 Android画板开发(三) 撤销反撤销功能实现 Android画板开发(四) 添加背景和保存画板内容为图片 A ...

  4. Android wifi探究二:Wifi framework层源码分析

    上一篇博客初步认识了wpa_supplicant的作用和使用方法,并且尝试着梳理了wifi的大框架,不过,java层的框架我们忽略了,没有分析,也就是说上一篇博客简单的指出了wifi代码的大框架,那么 ...

  5. android 获取wifi的加密类型,Android WIFI开发:获取wifi列表,连接指定wifi,获取wifi加密方式,监听wifi网络变化等...

    下面是 Android 开发中 WiFi 的常用配置,如:获取当前 WiFi ,扫描 WiFi 获取列表,连接指定 WiFi ,监听网络变化等等. 下面是效果图: GitHub 下载地址:https: ...

  6. Android SDK开发技术分享

    最近在工作中负责统一支付平台的SDK开发部分,就此总结下SDK开发的技术点.注意事项.与普通app开发的差别,作为自我总结,也作为公司内部互相学习的分享,希望有Android开发需求或者对Androi ...

  7. 【Android SDK 开发】Android SDK开发技术分享

    原文地址:https://blog.csdn.net/zhangxinjin/article/details/51602577 最近在工作中负责统一支付平台的SDK开发部分,就此总结下SDK开发的技术 ...

  8. Android 蓝牙开发(二) --手机与蓝牙音箱配对,并播放音频

    Android 蓝牙开发(一) – 传统蓝牙聊天室 Android 蓝牙开发(三) – 低功耗蓝牙开发 项目工程BluetoothDemo 上一章中,我们已经学习了传统蓝牙的开发,这一章,我们来学习如 ...

  9. 【Android游戏开发二十二】(图文详解)游戏中灵活实现动画播放!简述J2me的游戏类库与Android游戏开发!

    本站文章均为 李华明Himi 原创,转载务必在明显处注明:(作者新浪微博: @李华明Himi ) 转载自[黑米GameDev街区] 原文链接: http://www.himigame.com/andr ...

  10. Android WifiDisplay分析二:Wifi display连接过程

    版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] WifiDisplay之P2P的建立 WifiDisplay之RTSP server的创建 这一章中我们来看Wifi Displ ...

最新文章

  1. WordPress工作原理之程序文件执行顺序
  2. NLP中文面试学习资料:面向算法面试,理论代码俱全,登上GitHub趋势榜
  3. 集合嵌套存储和遍历元素的示例
  4. 击败李世石后,人工智能转战医疗:用大数据诊断眼科疾病
  5. java替换html样式_Java Jsoup替换标签的CSS样式
  6. angular分页插件tm.pagination 解决触发二次请求的问题
  7. 计算机博士一年看多少篇文献,博士生真的要一天看20篇文献吗?
  8. 轻量化网络:SqueezeNet
  9. ORACLE PL/SQ入门
  10. 界址点圆圈怎么生成_手机联系人怎么加入黑名单
  11. JavaEE下关于JSF开发的一些知识点小节
  12. 追溯计算机的本源,读电路与系统简史
  13. 【JSON】JSON入门详解(一)
  14. 电商设计——3、点线面及光影
  15. 群晖jellyfin外网访问
  16. MATLAB与安捷伦lan口通讯,matlab与安捷伦示波器通讯问题
  17. 转:曾国藩:天道酬勤,地道酬德,人道酬诚
  18. 云计算“战场”硝烟弥漫,巨头争相降价抢市场
  19. 免杀入门(基础理论)
  20. 十三、Cadence ic 617 CDB转OA

热门文章

  1. ACM-计算几何之改革春风吹满地——hdu2036
  2. 视频教程-软件项目管理实战-研发管理
  3. Ubuntu启动黑屏与安装黑屏
  4. 多线程的创建方式和解决线程安全问题
  5. 基于误差状态的卡尔曼滤波ESKF
  6. python颜色填充函数_【图像后处理】python+OpenCV填充孔洞
  7. 内蒙冤杀案拖8年未重审 原办案者多居要职
  8. 2022云南昆明市农村信用合作社联合社招聘精选题及答案
  9. 在Edge浏览器中启用Internet Explorer 模式
  10. 最成熟的前端换肤方案(主题切换)