Android Q 版本自动连接指定wifi

本文介绍了如何在Android Q设备上,通过匹配SSID并解析Wi-Fi信息,实现进入特定WiFi范围即自动连接的功能。代码中展示了如何创建Wi-Fi配置并调用`connect()`方法。还涉及了部分Wi-FiInfo解析的调整和判断是否已连接的方法。

需求

     进入wifi范围自动对该wifi进行连接。

Android 版本:

     Android Q

 

方案:

     通过SSID匹配,然后对wifi info进行解析,再进行连接。

代码:

diff --git a/alps/frameworks/opt/net/wifi/service/java/com/android/server/wifi/ScanRequestProxy.java b/alps/frameworks/opt/net/wifi/service/java/com/android/server/wifi/ScanRequestProxy.java
index efbb7b6..24542f2 100644
--- a/alps/frameworks/opt/net/wifi/service/java/com/android/server/wifi/ScanRequestProxy.java
+++ b/alps/frameworks/opt/net/wifi/service/java/com/android/server/wifi/ScanRequestProxy.java
@@ -44,6 +44,22 @@ import java.util.List;
 
 import javax.annotation.concurrent.NotThreadSafe;
 
+import android.provider.Settings;
+import java.util.regex.Pattern;
+import android.text.TextUtils;
+
+//Monkey wifi connected
+import android.net.ConnectivityManager;
+import android.net.NetworkSpecifier;
+import android.net.NetworkRequest;
+import android.net.wifi.WifiNetworkSpecifier;
+import android.os.PatternMatcher;
+import android.net.NetworkCapabilities;
+import android.net.Network;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiEnterpriseConfig;
+
+
 /**
  * This class manages all scan requests originating from external apps using the
  * {@link WifiManager#startScan()}.
@@ -87,6 +103,8 @@ public class ScanRequestProxy {
     private final FrameworkFacade mFrameworkFacade;
     private final ThrottleEnabledSettingObserver mThrottleEnabledSettingObserver;
     private WifiScanner mWifiScanner;
+	
+	private boolean mIsScanProcessingComplete = true;
 
     // Verbose logging flag.
     private boolean mVerboseLoggingEnabled = false;
@@ -131,12 +149,38 @@ public class ScanRequestProxy {
             if (mVerboseLoggingEnabled) {
                 Log.d(TAG, "Received " + scanResults.length + " scan results");
             }
+			WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+			ArrayList<ScanResult> TempList2G = new ArrayList<ScanResult>();
+                for (int i = 0; i < scanResults.length; i++) {
+                    if (scanResults[i].frequency > 2400 && scanResults[i].frequency < 2500) {
+                        TempList2G.add(scanResults[i]);
+                    }
+					Log.d("monkey_wifi","isWifiConnected:"+isWifiConnected(mContext));
+					Log.d("monkey_wifi","scanResults[i]:"+scanResults[i]);
+					
+					// Monkey.20201218 wifi connected SSID
+					if(scanResults[i].SSID.equals("wifi name") && !isWifiConnected(mContext)){
+						
+						WifiConfiguration wifiNewConfiguration = createWifiInfo("wifi name","",2);
+						// WifiConfiguration wifiNewConfiguration = scanResults[i];
+						mWifiManager.save(wifiNewConfiguration,null);
+						mWifiManager.connect(wifiNewConfiguration,null);
+					}
+                }
+                Log.e(TAG, "TempList2G = " + TempList2G.toString());
+                ScanResult[] temp = TempList2G.toArray(new ScanResult[TempList2G.size()]);
+               /*  mLastScanResults.clear();
+                mLastScanResults.addAll(Arrays.asList(temp));
+                sendScanResultBroadcastIfScanProcessingNotComplete(true); */
+			
             // Only process full band scan results.
             if (scanData.getBandScanned() == WifiScanner.WIFI_BAND_BOTH_WITH_DFS) {
                 // Store the last scan results & send out the scan completion broadcast.
                 mLastScanResults.clear();
-                mLastScanResults.addAll(Arrays.asList(scanResults));
-                sendScanResultBroadcast(true);
+				// mLastScanResults.addAll(Arrays.asList(scanResults));
+                // sendScanResultBroadcast(true);
+                mLastScanResults.addAll(Arrays.asList(temp));
+                sendScanResultBroadcastIfScanProcessingNotComplete(true);
             }
         }
 
@@ -269,7 +313,16 @@ public class ScanRequestProxy {
         }
         return mWifiScanner != null;
     }
-
+	
+	private void sendScanResultBroadcastIfScanProcessingNotComplete(boolean scanSucceeded) {
+        /* if (mIsScanProcessingComplete) {
+            Log.i(TAG, "No ongoing scan request. Don't send scan broadcast.");
+            return;
+        } */
+        sendScanResultBroadcast(scanSucceeded);
+        mIsScanProcessingComplete = true;
+    }
+	
     /**
      * Method that lets public apps know that scans are available.
      *
@@ -525,4 +578,74 @@ public class ScanRequestProxy {
         }
         mLastScanTimestampsForFgApps.remove(Pair.create(uid, packageName));
     }
+	// Monkey
+	private 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 + "\"";
+			if (Type == 0) {
+				// config.wepKeys[0] = "\"" + "\"";
+				config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+				// config.wepTxKeyIndex = 0;
+			} else if (Type == 1) {
+				Log.i("monkey_wifi", "WEP_config : ");
+				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;
+			} else if (Type == 2) {
+				Log.i("monkey_wifi", "WPA_config : ");
+				config.hiddenSSID = false;
+				config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+				config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+				WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+				enterpriseConfig.setIdentity(SSID);//
+				// enterpriseConfig.setPassword(wifiConnDO.getPassword());//
+				enterpriseConfig.setAnonymousIdentity("");//
+				enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.SIM);//
+				// enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.SIM);
+				enterpriseConfig.setCaCertificateAlias("");
+				enterpriseConfig.setClientCertificateAlias("");
+				enterpriseConfig.setIdentity("");
+				enterpriseConfig.setCaPath("");
+				enterpriseConfig.setDomainSuffixMatch("");
+				enterpriseConfig.setSimNum(0);
+				// enterpriseConfig.setPassword("");
+				
+				config.enterpriseConfig = enterpriseConfig;
+			} else {
+				return null;
+			}
+			Log.i("monkey_wifi", "WIFI_config : "+config);
+			return config;
+
+	}
+	
+    public static boolean isWifiConnected(Context context) {
+        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
+        if(manager != null) {
+            NetworkCapabilities cap = manager.getNetworkCapabilities(manager.getActiveNetwork());
+            return (cap != null) && cap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
+        }
+        return false;
+    }
+	//end
+	
+
+
 }

注:部分wifi info的解析方式差异

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧时旅人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值