Question

I have 2 buttons in my app.

button 1: connect wifi button 2: create a client socket

with individual 2 buttons this functionality works.

void WifiConnect() { String networkSSID = "HI-LINK_DA79"; String networkPass = "12345678"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; //ssid must be in quotes conf.preSharedKey = "\""+ networkPass +"\"";

    WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE); 
    int  r1 =-1;
     r1= wifiManager.addNetwork(conf);
     Log.d("Client", "add Network returned " + r1 );

    boolean b = wifiManager.enableNetwork(r1, true);        
    Log.d("Client", "enableNetwork returned " + b );

    boolean d= wifiManager.reconnect();
   Log.d("Client", "wifiManager.reconnect() returned " + d )


}

`Button.OnClickListener buttonWifiConnectOnClickListener = new Button.OnClickListener() {

    public void onClick(View v) {

    WifiConnect();


    }
};

Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener() {

    public void onClick(View v) {

        if (socket == null) { 
            Log.i("Client", "socket():Creating --");
            new Thread(new ClientThread()).start();
            //connect.setText("Disconnect");
        }
        else
        {
        try {
            socket.close();
            socket=null;
            Log.i("Client", "socket():closed --");
        //  connect.setText("Connect");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        }


    }
};

`

But this don't work if I combine them in one button click `Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener() {

    public void onClick(View v) {

        WifiConnect();    //WiFi connect

        if (socket == null) { 
            Log.i("Client", "socket():Creating --");
            new Thread(new ClientThread()).start();
            //connect.setText("Disconnect");
        }
        else
        {
        try {
            socket.close();
            socket=null;
            Log.i("Client", "socket():closed --");
        //  connect.setText("Connect");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        }


    }
};

`

looks like my thread to create socket is not not called here, don't know why.

Was it helpful?

Solution

If you want both operation to work on a single button click, then add a BroadcastReceiver for listening to Wifi connection state, as shown in below. & in the onReceive() method do the socket connection. Your socket connection is not working when in same button click because Wifi connection takes time & without first Wifi being connected socket connection is being created, so it might throw an exception.

Checking for whether Wi-Fi is enabled, that doesn't necessarily mean that it's connected. It just means that Wi-Fi mode on the phone is enabled and able to connect to Wi-Fi networks.

This is how listening for actual Wi-Fi connections in Broadcast Receiver:

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {     
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
        NetworkInfo netInfo = conMan.getActiveNetworkInfo();
        if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            Log.d("WifiReceiver", "Have Wifi Connection");
                    //If connected do socket connection here
            }
        else
            Log.d("WifiReceiver", "Don't have Wifi Connection");    
    }   
};

In order to access the active network info you need to add the following uses-permission to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And the following intent receiver (or you could add this programmatically...)

<!-- Receive Wi-Fi connection state changes -->
<receiver android:name=".WifiReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

& make sure that network activity is done on other thread than Main thread. Also you'll have to register & unregister the BroadcastReceiver appropriately. Don't forget to unregister it when not needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top