我正在尝试在android 10 (API级别29)中连接特定的wifi网络。我已经为下面给出了一个函数,
private void connectToWifi(final String ssid, String password) { count=0; wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()){ wifiManager.setWifiEnabled(true); System.out.println("Wifi is enabled"); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { System.out.println("Android sdk version is 29 above"); final WifiNetworkSuggestion suggestion1 = new WifiNetworkSuggestion.Builder() .setSsid(ssid) .setIsAppInteractionRequired(true) // Optional (Needs location permission) .build(); final WifiNetworkSuggestion suggestion2 = new WifiNetworkSuggestion.Builder() .setSsid(ssid) .setWpa2Passphrase(password) .setIsAppInteractionRequired(true) // Optional (Needs location permission) .build(); final WifiNetworkSuggestion suggestion3 = new WifiNetworkSuggestion.Builder() .setSsid(ssid) .setWpa3Passphrase(password) .setIsAppInteractionRequired(true) // Optional (Needs location permission) .build(); final List<WifiNetworkSuggestion> suggestionsList = new ArrayList<WifiNetworkSuggestion>(); suggestionsList.add(suggestion1); suggestionsList.add(suggestion2); suggestionsList.add(suggestion3); WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder(); builder.setSsid(ssid); builder.setWpa2Passphrase(password); final int status = wifiManager.addNetworkSuggestions(suggestionsList); if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) { System.out.println("Status:" +status); // do error handling here… WifiNetworkSpecifier wifiNetworkSpecifier = builder.build(); NetworkRequest.Builder networkRequestBuilder1 = new NetworkRequest.Builder(); networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier); NetworkRequest nr = networkRequestBuilder1.build(); final ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { super.onAvailable(network); Log.d("MainActivity", "onAvailable:" + network); cm.bindProcessToNetwork(network); @Override public void onLosing(@NonNull Network network, int maxMsToLive) { super.onLosing(network, maxMsToLive); System.out.println("onLosing" + network); @Override public void onLost(@NonNull Network network) { super.onLost(network); System.out.println("onLost" + network); @Override public void onUnavailable() { super.onUnavailable(); System.out.println("onUnavaliable"); Toast.makeText(MainActivity.this, "Your Password is incorrect", Toast.LENGTH_SHORT).show(); cm.requestNetwork(nr, networkCallback); final IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION); final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) { System.out.println("ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION Failed"); return; }else { System.out.println("Connection Successful.........."); // Post connection getApplicationContext().registerReceiver(broadcastReceiver, intentFilter); } else{ try { WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = "\"" + ssid + "\""; wifiConfig.preSharedKey = "\"" + password + "\""; int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); IntentFilter wifiStatusIntentFilter = new IntentFilter(); wifiStatusIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); wifiStatusIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); //wifiStatusIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String str = wifiInfo.getSSID().replace("\"", ""); switch (info.getState()) case CONNECTING: System.out.println("Connecting"); System.out.print("\nWifiInfo: " +str); System.out.print("\nUserInput SSID: " +ssid); break; case CONNECTED: if(str.equals(ssid)) { System.out.println("Connected ... str.equals(ssid) " + count); System.out.println("Connected" ); passwordIsCoorectError="correct"; returnWifConnection("1234", "correct"); // return "correct"; //count = 1; break; case DISCONNECTING: System.out.println("Disconnecting"); break; case DISCONNECTED: System.out.println("Disconnected"); System.out.println("Disconnected->str" +str); System.out.println("Disconnected->ssid" +ssid); count ++; if(str.equals(ssid)) System.out.println("count str.equals(ssid) "+count); // count = 1; if(count==5) System.out.println("count===5 "+count); // Toast.makeText(MainActivity.this, "Your Password is incorrect", Toast.LENGTH_SHORT).show(); passwordIsCoorectError="wrong"; returnWifConnection("1234", "wrong"); // return "wrong"; break; case SUSPENDED: System.out.println("Suspended"); break; getApplicationContext().registerReceiver(broadcastReceiver, wifiStatusIntentFilter); } catch (Exception e) { e.printStackTrace(); }
我的代码没有为此验证提供正确的结果。实际上,当我用错误的密码连接到wifi,并尝试用正确的密码再次连接时,我遇到了问题。Wifi未连接,控件始终在NetworkCallback类的onUnavailable()方法中。请帮我找到一个解决方案。
发布于 2020-12-16 13:38:49
final NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder() .setSsidPattern(new PatternMatcher("wifissid", PatternMatcher.PATTERN_PREFIX)) .setWpa2Passphrase("wifipassword") .build(); final NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .setNetworkSpecifier(specifier) .build(); final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(@NonNull Network network) {