赞
踩
广播过滤Action
-
- WifiManager.NETWORK_STATE_CHANGED_ACTION
工具类
- package com.yw.wifipage.wifi;
-
- import android.content.Context;
- import android.content.IntentFilter;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.net.wifi.WifiConfiguration;
- import android.net.wifi.WifiInfo;
- import android.net.wifi.WifiManager;
- import android.os.Handler;
-
- import com.yw.wifipage.receiver.WifiChangeReceiver;
-
- public class WifiConnectUtil {
-
- private boolean isConnect = false;
- private WifiChangeReceiver receiver;
-
- public void connect(Context context, String ssid, String bssid, String password, int timeOut, IConnectListener listener) {
-
- String mssid = ssid.replace("\"", "");
-
- WifiConfiguration wifiCong = new WifiConfiguration();
- wifiCong.allowedAuthAlgorithms.clear();
- wifiCong.allowedGroupCiphers.clear();
- wifiCong.allowedKeyManagement.clear();
- wifiCong.allowedPairwiseCiphers.clear();
- wifiCong.allowedProtocols.clear();
- wifiCong.SSID = "\"" + mssid + "\"";
- wifiCong.BSSID = bssid;
- wifiCong.preSharedKey = "\"" + password + "\"";//WPA-PSK密码
- wifiCong.hiddenSSID = false;
- wifiCong.status = WifiConfiguration.Status.ENABLED;
- int id = MyNetworkUtil.getInstance().getWifiManager().addNetwork(wifiCong);
- MyNetworkUtil.getInstance().getWifiManager().enableNetwork(id, true);
-
- //注册广播快速监听连接状态
- receiver = new WifiChangeReceiver(networkInfo -> {
- if (networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
- WifiInfo wifiInfo = MyNetworkUtil.getInstance().getWifiInfo();
- if (wifiInfo.getSSID().replace("\"", "").equals(mssid)) {
- isConnect = true;
- if (receiver != null) {
- context.unregisterReceiver(receiver);
- receiver = null;
- listener.onConnected();
- }
- }
- }
- });
-
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- context.registerReceiver(receiver, intentFilter);
- //延时监听变化
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (isConnect) {
- return;
- }
- if (receiver != null) {
- context.unregisterReceiver(receiver);
- }
- MyNetworkUtil.getInstance().getWifiManager().removeNetwork(id);
- MyNetworkUtil.getInstance().getWifiManager().reconnect();
- listener.onConnectFail();
- }
- }, timeOut);
- }
-
-
- public interface IConnectListener {
- void onConnected();
- void onConnectFail();
- }
- }
广播接收器
- package com.yw.wifipage.receiver;
-
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.net.NetworkInfo;
- import android.net.wifi.WifiManager;
- import android.os.Parcelable;
-
- public class WifiChangeReceiver extends BroadcastReceiver {
- private String TAG = "WifiChangeReceiver";
- private IWIfiChangeCallBack iwIfiChangeCallBack;
-
- public WifiChangeReceiver(IWIfiChangeCallBack iwIfiChangeCallBack) {
- this.iwIfiChangeCallBack = iwIfiChangeCallBack;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- Parcelable extra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
- if (extra != null) {
- NetworkInfo networkInfo = (NetworkInfo) extra;
- if (networkInfo != null) {
- iwIfiChangeCallBack.onChange(networkInfo);
- }
- }
- }
- }
-
- import android.annotation.SuppressLint;
- import android.content.Context;
- import android.location.LocationManager;
- import android.net.ConnectivityManager;
- 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.os.Handler;
- import android.os.Message;
- import android.util.Log;
-
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.Inet6Address;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.util.Enumeration;
- import java.util.List;
-
- public class MyNetworkUtil {
- private static MyNetworkUtil myWifiUtil;
- private WifiManager wifiManager;
- private ConnectivityManager connectivityManager;
- private Thread pingThread;
- private boolean startPing = false;
-
- private MyNetworkUtil() {
-
- }
-
- public static MyNetworkUtil getInstance() {
- if (myWifiUtil == null) {
- myWifiUtil = new MyNetworkUtil();
- }
- return myWifiUtil;
- }
-
- public WifiManager getWifiManager() {
- if (wifiManager == null) {
- wifiManager = (WifiManager) MyApplication.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
- }
- return wifiManager;
- }
-
- public ConnectivityManager getConnectivityManager() {
- if (connectivityManager == null) {
- connectivityManager = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
- }
- return connectivityManager;
- }
-
- public NetworkInfo getNetworkInfo() {
- return getConnectivityManager().getActiveNetworkInfo();
- }
-
- public WifiInfo getWifiInfo() {
- return getWifiManager().getConnectionInfo();
- }
-
- /**
- * 判断 wifi 是否是 5G 频段.
- * 需要权限:
- * <uses-permission android:name="android.permission.INTERNET" />
- * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- */
- public boolean isWifi5G(Object obj) {
- int freq = 0;
- if (obj instanceof WifiInfo) {
- if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
- WifiInfo wifiInfo = (WifiInfo) obj;
- freq = wifiInfo.getFrequency();
- }
- } else if (obj instanceof ScanResult) {
- ScanResult scanResult = (ScanResult) obj;
- freq = scanResult.frequency;
- }
- return freq > 4900 && freq < 5900;
- }
-
-
- /**
- * 手机是否开启位置服务,如果没有开启那么所有app将不能使用定位功能
- */
- public boolean isLocServiceEnable(Context context) {
- LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
- boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
- if (gps || network) {
- return true;
- }
- return false;
- }
-
- /**
- * 检查wifi是否可用
- */
- public boolean checkWifiIsEnable() {
- WifiManager wifiManager = (WifiManager) MyApplication.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
- return null != wifiManager && wifiManager.isWifiEnabled();
- }
-
-
- /**
- * Get Ip address 自动获取IP地址
- *
- * @throws SocketException
- */
- public String getIpAddress(String ipType) {
- String hostIp = "0.0.0.0";
- try {
- Enumeration nis = NetworkInterface.getNetworkInterfaces();
- InetAddress ia = null;
- while (nis.hasMoreElements()) {
- NetworkInterface ni = (NetworkInterface) nis.nextElement();
- if (ni.getName().equals(ipType)) {
- Enumeration<InetAddress> ias = ni.getInetAddresses();
- while (ias.hasMoreElements()) {
- ia = ias.nextElement();
- if (ia instanceof Inet6Address) {
- continue;// skip ipv6
- }
- String ip = ia.getHostAddress();
- // 过滤掉127段的ip地址
- if (!"127.0.0.1".equals(ip)) {
- hostIp = ia.getHostAddress();
- break;
- }
- }
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- }
- Log.d("vivi", "get the IpAddress--> " + hostIp + "");
- return hostIp;
- }
-
- public String getSecurity(String ssid) {
- ssid = ssid.replace("\"", "");
-
- WifiConfiguration config = null;
-
- @SuppressLint("MissingPermission") List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
- for (WifiConfiguration configuration : configurations) {
- if (configuration.SSID.replace("\"", "").equals(ssid)) {
- config = configuration;
- break;
- }
- }
-
- if (config != null) {
- if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
- //return SECURITY_PSK;
- return "WPA/WPA2 PSK";
- }
- if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
- return "WEP";
- }
- }
-
- return "unknow";
- }
-
-
- public String getLevel(int level) {
- if (level >= 4) {
- return "强";
- } else if (level >= 2 && level < 4) {
- return "信号稳定";
- }
- return "弱";
- }
-
-
- public void startPing(String host, Handler handler) {
- startPing = true;
- pingThread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- while (startPing) {
- //-c 3 3次
- //-w 5 5秒超时
- Process exec = Runtime.getRuntime().exec("ping " + host);
- InputStream inputStream = exec.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- String line;
- while ((line = reader.readLine()) != null && startPing) {
- System.out.println("ping====" + line);
- if (line.contains("time=")) {
- String ms = line.split("time=")[1];
- Message message = handler.obtainMessage();
- message.what = 0;
- message.obj = ms;
- handler.sendMessage(message);
- }
- }
- reader.close();
- }
- // System.out.println("终止ping");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- pingThread.start();
- }
-
- public void stopPing() {
- startPing = false;
- }
-
- }
使用方法
- new WifiConnectUtil().connect(context, SSID, BSSID, password, 10000,
- new WifiConnectUtil.IConnectListener() {
- @Override
- public void onConnected() {
- Toast.makeText(context, "连接成功", Toast.LENGTH_SHORT).show();
-
- }
-
- @Override
- public void onConnectFail() {
- Toast.makeText(context, "密码错误", Toast.LENGTH_SHORT).show();
-
- }
- });
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。