-1

I have been trying to connect to a HotSpot created on another device by using the WifiManager class. I have gone through and used the code from this answer. So finally my code looks like this :

    for( ScanResult i : list ) {
        Toast.makeText(context, i.SSID, Toast.LENGTH_SHORT).show();
        if(i.SSID != null && (i.SSID.startsWith("SMSKCM877-") && i.SSID.endsWith("-MSDBP2016"))) {
            // Toast.makeText(context, "Found Match", Toast.LENGTH_SHORT);
             conf.SSID="\""+i.SSID+"\"";
             conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
             wifiManager.addNetwork(conf);
             int networkID=wifiManager.addNetwork(conf);
             wifiManager.disconnect();               
             wifiManager.enableNetwork(networkID, true);
             wifiManager.reconnect();    
             String ipStr="";
             DhcpInfo sinfo=wifiManager.getDhcpInfo();
             int ip=sinfo.serverAddress;
             ipStr =  String.format("%d.%d.%d.%d",
                             (ip & 0xff),   
                             (ip >> 8 & 0xff),             
                             (ip >> 16 & 0xff),    
                             (ip >> 24 & 0xff));
             Log.e("sg", ipStr);                                 
             Toast.makeText(context, ipStr+"", Toast.LENGTH_LONG).show();            
             startConnect s=new startConnect(ipStr,context);
             s.execute(); 
             return true;
        }           
     }

But the problem I am facing is that when I try to connect for the first time the ipstrgenerated is always 0.0.0.0 . Retrying a few times gives me the correct address and everything goes smoothly afterwards. Any idea why this problem occurs?

Thanks in advance.

Community
  • 1
  • 1
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29

1 Answers1

0

Just register Broadcast Receiver for WifiManager.NETWORK_STATE_CHANGED_ACTION and wait for CONNECTED event.

IntentFilter intentfilterState = (IntentFilter)new IntentFilter();
intentfilterState.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

BroadcastReceiver nsca = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //your code goes here
        }
}

_context.registerReceiver(nsca, intentfilterState);
Rishabh Jain
  • 81
  • 1
  • 5