Android Q 10 Connect to network WifiNetworkSpecifier

后端 未结 2 1720
春和景丽
春和景丽 2020-12-30 10:45

Since Android Q doesn\'t allow the WifiManager to add Networks, they gave the advise to use WifiNetworkSpecifier instead. With the WifiNetworkSuggestionBuilder I was alread

相关标签:
2条回答
  • 2020-12-30 11:14

    I tried this code its working fine

    WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
    builder.setSsid("abcdefgh");
    builder.setWpa2Passphrase("1234567890");
    
    WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
    NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
    networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);     
    networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
    NetworkRequest networkRequest = networkRequestBuilder.build();
    ConnectivityManager cm = (ConnectivityManager) 
               App.getInstance().getBaseContext().getApplicationContext()
              .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
        cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
               super.onAvailable(network);
        cm.bindProcessToNetwork(network)
            }});
    
    0 讨论(0)
  • 2020-12-30 11:33

    A bit late to the party, but maybe it will help someone else that encounters this problem.

    It seems like you are right. In android Q once the app is killed, the system automatically disconnects the WiFi network we've connected to through WifiNetworkSpecifier and there is no way to prevent the system from doing so.

    The best solution I've come up with, is using WifiNetworkSpecifier with WifiNetworkSuggestion. This allows us to use WifiNetworkSpecifier while we are using our app, and suggest wifi networks for the system to auto connect to once the system disconnects from our WiFi due to the app being terminated.

    Here is some sample code:

        WifiNetworkSuggestion.Builder builder = new WifiNetworkSuggestion.Builder()
            .setSsid("YOUR_SSID")
            .setWpa2Passphrase("YOUR_PASSWORD")
        WifiNetworkSuggestion suggestion = builder.build();
    
        ArrayList<WifiNetworkSuggestion> list = new ArrayList<>();
        list.add(suggestion);
    
        WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        int status = manager.addNetworkSuggestions(list);
    
        if (status == STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
            //We have successfully added our wifi for the system to consider
        }
    

    Cheers,

    0 讨论(0)
提交回复
热议问题