3

While using the wifi manager to connect to Esp8266 I suddenly started receiving a connection error. The output says it all. I can scan and find the correct SSID, but when connecting to it either the connection is refused or it just can't connect. Looking at the documentation it looks like wifi manager is on its way out? and WifiNetworkSpecifier is what should be used? But that only works for phones using API29 and up. I need this to work on all phones

I have connected to the esp8266 from my computer and am getting a response back - no connection issues with the Esp8266

public class ChooseDevice extends AppCompatActivity {

    private WifiManager wifiManager;
    private ListView listView;
    private ArrayList<String> arrayList = new ArrayList<>();
    private ArrayAdapter adapter;
    TextView TV_noDevicesFound;

    BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            List<ScanResult> results = wifiManager.getScanResults();
            unregisterReceiver(this);

            for (ScanResult scanResult : results) {
                Log.d("Here!!", scanResult.SSID);
                if (scanResult.SSID.startsWith("Cessabit")) {
                    arrayList.add(scanResult.SSID);
                    adapter.notifyDataSetChanged();

                }
            }

            if (arrayList.size()==0){
                TV_noDevicesFound.setVisibility(View.VISIBLE);
            }else{
                TV_noDevicesFound.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_device);
        TV_noDevicesFound = findViewById(R.id.TV_noDevicesFound);
        listView = findViewById(R.id.deviceList);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String Device_SSID = listView.getItemAtPosition(position).toString();
                connectToDevice(Device_SSID);
                Intent intent = new Intent(ChooseDevice.this, ChooseWifi.class);
                startActivity(intent);
            }
        });

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);


        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }


        adapter = new ArrayAdapter<>(this, R.layout.layout_list_item, R.id.DeviceTxtView, arrayList);
        listView.setAdapter(adapter);
    }



    private void connectToDevice(String SSID) {
        WifiInfo connection;
        Log.d("Connecting To SSID: ", SSID);
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + SSID + "\"";
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int netID = wifiManager.addNetwork(conf);
        Log.d("netID", ""+netID);
        wifiManager.disconnect();
        wifiManager.enableNetwork(netID, true);
        wifiManager.reconnect();
        connection = wifiManager.getConnectionInfo();
        String ConnectedSSID = connection.getSSID();
        Log.d("Connected To SSID : ", ConnectedSSID);

    }

    @Override
    protected void onStop(){
        super.onStop();
        try{
            unregisterReceiver(wifiReceiver);
        }catch(final Exception exception){
            Log.d("Receiver try catch","cannot unregister receiver");
        }

    }
    @Override
    protected void onStart(){
        super.onStart();
        arrayList.clear();
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifiManager.startScan();
        Toast.makeText(this, "Scanning for Devices ..", Toast.LENGTH_SHORT).show();

    }


}

D/Connecting To SSID:: Cessabit-1111
I/zygote: Do partial code cache collection, code=107KB, data=80KB
I/zygote: After code cache collection, code=107KB, data=80KB
    Increasing code cache capacity to 512KB
D/netID: -1
V/NativeCrypto: Read error: ssl=0xec4b4768: I/O error during system call, Software caused connection abort
V/NativeCrypto: Write error: ssl=0xec4b4768: I/O error during system call, Broken pipe
V/NativeCrypto: SSL shutdown failed: ssl=0xec4b4768: I/O error during system call, Success
D/Connected To SSID :: <unknown ssid>
Jalpa Panchal
  • 8,251
  • 1
  • 11
  • 26
MarcC137
  • 31
  • 1
  • 2

1 Answers1

1

You have to do separate things for for Android 10 and above as API's have changed.

Use WifiNetworkSpecifier to send your requests. Use the network object provided in onAvailable().

    private void connectToDevice(String SSID) {
       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
           WifiInfo connection;
          Log.d("Connecting To SSID: ", SSID);
          WifiConfiguration conf = new WifiConfiguration();
          conf.SSID = "\"" + SSID + "\"";
          conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
          wifiManager = (WifiManager)  getApplicationContext().getSystemService(Context.WIFI_SERVICE);
          int netID = wifiManager.addNetwork(conf);
          Log.d("netID", ""+netID);
          wifiManager.disconnect();
          wifiManager.enableNetwork(netID, true);
          wifiManager.reconnect();
          connection = wifiManager.getConnectionInfo();
          String ConnectedSSID = connection.getSSID();
          Log.d("Connected To SSID : ", ConnectedSSID);
       } else {
              WifiNetworkSpecifier.Builder builder = new                   WifiNetworkSpecifier.Builder();
              builder.setSsid(SSID);

              WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();

             NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
          networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
               networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier);

              NetworkRequest networkRequest = networkRequestBuilder.build();
              ConnectivityManager cm = (ConnectivityManager)                context.getSystemService(Context.CONNECTIVITY_SERVICE);
             cm.requestNetwork(networkRequest, networkCallback);
            networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                //Use this network object to Send request. 
                //eg - Using OkHttp library to create a service request

                super.onAvailable(network);
            }
        };
       }

}

After you are done using the Wifi access point do

connectivityManager.unregisterNetworkCallback(networkCallback);

Anand Khinvasara
  • 618
  • 4
  • 17
  • 3
    This code does not work for me. Android 10 oneplus 7T. The window of authorization appears with the good ssid but when I click on connect, the process of connection begins 'obtaining address ip' then a toast "successful connection" and the pop up of authorization returns again ... – Aristide13 Oct 30 '19 at 11:36
  • 2
    I have the same problem on OnePlust 6T with Android 10. I get a popup to connect to the right network and then got the same "successful connection" and the same popup pops again. It is like a loop... – Vladimir Petrovski Jan 02 '20 at 16:12
  • Are you using the network object given onAvailable() callback? – Anand Khinvasara Jan 07 '20 at 21:07
  • 1
    Same thing is happening for me. Any solutions? – Anand Khinvasara Jan 08 '20 at 19:14
  • I get an error with your code: *Request not from foreground app or service. Rejecting request from *. I'm using a Wifi Broadcast Receiver in Android 10. – Luis A. Florit May 11 '20 at 21:48