当前位置:   article > 正文

Android 应用内连接指定 WIFI_android 连接指定wifi

android 连接指定wifi
广播过滤Action
  1. WifiManager.NETWORK_STATE_CHANGED_ACTION

工具类

  1. package com.yw.wifipage.wifi;
  2. import android.content.Context;
  3. import android.content.IntentFilter;
  4. import android.net.ConnectivityManager;
  5. import android.net.NetworkInfo;
  6. import android.net.wifi.WifiConfiguration;
  7. import android.net.wifi.WifiInfo;
  8. import android.net.wifi.WifiManager;
  9. import android.os.Handler;
  10. import com.yw.wifipage.receiver.WifiChangeReceiver;
  11. public class WifiConnectUtil {
  12. private boolean isConnect = false;
  13. private WifiChangeReceiver receiver;
  14. public void connect(Context context, String ssid, String bssid, String password, int timeOut, IConnectListener listener) {
  15. String mssid = ssid.replace("\"", "");
  16. WifiConfiguration wifiCong = new WifiConfiguration();
  17. wifiCong.allowedAuthAlgorithms.clear();
  18. wifiCong.allowedGroupCiphers.clear();
  19. wifiCong.allowedKeyManagement.clear();
  20. wifiCong.allowedPairwiseCiphers.clear();
  21. wifiCong.allowedProtocols.clear();
  22. wifiCong.SSID = "\"" + mssid + "\"";
  23. wifiCong.BSSID = bssid;
  24. wifiCong.preSharedKey = "\"" + password + "\"";//WPA-PSK密码
  25. wifiCong.hiddenSSID = false;
  26. wifiCong.status = WifiConfiguration.Status.ENABLED;
  27. int id = MyNetworkUtil.getInstance().getWifiManager().addNetwork(wifiCong);
  28. MyNetworkUtil.getInstance().getWifiManager().enableNetwork(id, true);
  29. //注册广播快速监听连接状态
  30. receiver = new WifiChangeReceiver(networkInfo -> {
  31. if (networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
  32. WifiInfo wifiInfo = MyNetworkUtil.getInstance().getWifiInfo();
  33. if (wifiInfo.getSSID().replace("\"", "").equals(mssid)) {
  34. isConnect = true;
  35. if (receiver != null) {
  36. context.unregisterReceiver(receiver);
  37. receiver = null;
  38. listener.onConnected();
  39. }
  40. }
  41. }
  42. });
  43. IntentFilter intentFilter = new IntentFilter();
  44. intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
  45. context.registerReceiver(receiver, intentFilter);
  46. //延时监听变化
  47. new Handler().postDelayed(new Runnable() {
  48. @Override
  49. public void run() {
  50. if (isConnect) {
  51. return;
  52. }
  53. if (receiver != null) {
  54. context.unregisterReceiver(receiver);
  55. }
  56. MyNetworkUtil.getInstance().getWifiManager().removeNetwork(id);
  57. MyNetworkUtil.getInstance().getWifiManager().reconnect();
  58. listener.onConnectFail();
  59. }
  60. }, timeOut);
  61. }
  62. public interface IConnectListener {
  63. void onConnected();
  64. void onConnectFail();
  65. }
  66. }

 广播接收器

  1. package com.yw.wifipage.receiver;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.net.NetworkInfo;
  6. import android.net.wifi.WifiManager;
  7. import android.os.Parcelable;
  8. public class WifiChangeReceiver extends BroadcastReceiver {
  9. private String TAG = "WifiChangeReceiver";
  10. private IWIfiChangeCallBack iwIfiChangeCallBack;
  11. public WifiChangeReceiver(IWIfiChangeCallBack iwIfiChangeCallBack) {
  12. this.iwIfiChangeCallBack = iwIfiChangeCallBack;
  13. }
  14. @Override
  15. public void onReceive(Context context, Intent intent) {
  16. Parcelable extra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
  17. if (extra != null) {
  18. NetworkInfo networkInfo = (NetworkInfo) extra;
  19. if (networkInfo != null) {
  20. iwIfiChangeCallBack.onChange(networkInfo);
  21. }
  22. }
  23. }
  24. }
  1. import android.annotation.SuppressLint;
  2. import android.content.Context;
  3. import android.location.LocationManager;
  4. import android.net.ConnectivityManager;
  5. import android.net.NetworkInfo;
  6. import android.net.wifi.ScanResult;
  7. import android.net.wifi.WifiConfiguration;
  8. import android.net.wifi.WifiInfo;
  9. import android.net.wifi.WifiManager;
  10. import android.os.Handler;
  11. import android.os.Message;
  12. import android.util.Log;
  13. import java.io.BufferedReader;
  14. import java.io.InputStream;
  15. import java.io.InputStreamReader;
  16. import java.net.Inet6Address;
  17. import java.net.InetAddress;
  18. import java.net.NetworkInterface;
  19. import java.net.SocketException;
  20. import java.util.Enumeration;
  21. import java.util.List;
  22. public class MyNetworkUtil {
  23. private static MyNetworkUtil myWifiUtil;
  24. private WifiManager wifiManager;
  25. private ConnectivityManager connectivityManager;
  26. private Thread pingThread;
  27. private boolean startPing = false;
  28. private MyNetworkUtil() {
  29. }
  30. public static MyNetworkUtil getInstance() {
  31. if (myWifiUtil == null) {
  32. myWifiUtil = new MyNetworkUtil();
  33. }
  34. return myWifiUtil;
  35. }
  36. public WifiManager getWifiManager() {
  37. if (wifiManager == null) {
  38. wifiManager = (WifiManager) MyApplication.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
  39. }
  40. return wifiManager;
  41. }
  42. public ConnectivityManager getConnectivityManager() {
  43. if (connectivityManager == null) {
  44. connectivityManager = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
  45. }
  46. return connectivityManager;
  47. }
  48. public NetworkInfo getNetworkInfo() {
  49. return getConnectivityManager().getActiveNetworkInfo();
  50. }
  51. public WifiInfo getWifiInfo() {
  52. return getWifiManager().getConnectionInfo();
  53. }
  54. /**
  55. * 判断 wifi 是否是 5G 频段.
  56. * 需要权限:
  57. * <uses-permission android:name="android.permission.INTERNET" />
  58. * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  59. * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  60. * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  61. */
  62. public boolean isWifi5G(Object obj) {
  63. int freq = 0;
  64. if (obj instanceof WifiInfo) {
  65. if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
  66. WifiInfo wifiInfo = (WifiInfo) obj;
  67. freq = wifiInfo.getFrequency();
  68. }
  69. } else if (obj instanceof ScanResult) {
  70. ScanResult scanResult = (ScanResult) obj;
  71. freq = scanResult.frequency;
  72. }
  73. return freq > 4900 && freq < 5900;
  74. }
  75. /**
  76. * 手机是否开启位置服务,如果没有开启那么所有app将不能使用定位功能
  77. */
  78. public boolean isLocServiceEnable(Context context) {
  79. LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  80. boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  81. boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  82. if (gps || network) {
  83. return true;
  84. }
  85. return false;
  86. }
  87. /**
  88. * 检查wifi是否可用
  89. */
  90. public boolean checkWifiIsEnable() {
  91. WifiManager wifiManager = (WifiManager) MyApplication.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
  92. return null != wifiManager && wifiManager.isWifiEnabled();
  93. }
  94. /**
  95. * Get Ip address 自动获取IP地址
  96. *
  97. * @throws SocketException
  98. */
  99. public String getIpAddress(String ipType) {
  100. String hostIp = "0.0.0.0";
  101. try {
  102. Enumeration nis = NetworkInterface.getNetworkInterfaces();
  103. InetAddress ia = null;
  104. while (nis.hasMoreElements()) {
  105. NetworkInterface ni = (NetworkInterface) nis.nextElement();
  106. if (ni.getName().equals(ipType)) {
  107. Enumeration<InetAddress> ias = ni.getInetAddresses();
  108. while (ias.hasMoreElements()) {
  109. ia = ias.nextElement();
  110. if (ia instanceof Inet6Address) {
  111. continue;// skip ipv6
  112. }
  113. String ip = ia.getHostAddress();
  114. // 过滤掉127段的ip地址
  115. if (!"127.0.0.1".equals(ip)) {
  116. hostIp = ia.getHostAddress();
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. } catch (SocketException e) {
  123. e.printStackTrace();
  124. }
  125. Log.d("vivi", "get the IpAddress--> " + hostIp + "");
  126. return hostIp;
  127. }
  128. public String getSecurity(String ssid) {
  129. ssid = ssid.replace("\"", "");
  130. WifiConfiguration config = null;
  131. @SuppressLint("MissingPermission") List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
  132. for (WifiConfiguration configuration : configurations) {
  133. if (configuration.SSID.replace("\"", "").equals(ssid)) {
  134. config = configuration;
  135. break;
  136. }
  137. }
  138. if (config != null) {
  139. if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
  140. //return SECURITY_PSK;
  141. return "WPA/WPA2 PSK";
  142. }
  143. if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
  144. return "WEP";
  145. }
  146. }
  147. return "unknow";
  148. }
  149. public String getLevel(int level) {
  150. if (level >= 4) {
  151. return "强";
  152. } else if (level >= 2 && level < 4) {
  153. return "信号稳定";
  154. }
  155. return "弱";
  156. }
  157. public void startPing(String host, Handler handler) {
  158. startPing = true;
  159. pingThread = new Thread(new Runnable() {
  160. @Override
  161. public void run() {
  162. try {
  163. while (startPing) {
  164. //-c 3 3次
  165. //-w 5 5秒超时
  166. Process exec = Runtime.getRuntime().exec("ping " + host);
  167. InputStream inputStream = exec.getInputStream();
  168. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  169. String line;
  170. while ((line = reader.readLine()) != null && startPing) {
  171. System.out.println("ping====" + line);
  172. if (line.contains("time=")) {
  173. String ms = line.split("time=")[1];
  174. Message message = handler.obtainMessage();
  175. message.what = 0;
  176. message.obj = ms;
  177. handler.sendMessage(message);
  178. }
  179. }
  180. reader.close();
  181. }
  182. // System.out.println("终止ping");
  183. } catch (Exception e) {
  184. e.printStackTrace();
  185. }
  186. }
  187. });
  188. pingThread.start();
  189. }
  190. public void stopPing() {
  191. startPing = false;
  192. }
  193. }

使用方法

  1. new WifiConnectUtil().connect(context, SSID, BSSID, password, 10000,
  2. new WifiConnectUtil.IConnectListener() {
  3. @Override
  4. public void onConnected() {
  5. Toast.makeText(context, "连接成功", Toast.LENGTH_SHORT).show();
  6. }
  7. @Override
  8. public void onConnectFail() {
  9. Toast.makeText(context, "密码错误", Toast.LENGTH_SHORT).show();
  10. }
  11. });

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/710146
推荐阅读
相关标签
  

闽ICP备14008679号