TechChain
TechChain

Reputation: 8942

Automatically connect to wifi network in android?

I am develping an app in which whenever wifi turned on then in background app should be to connect to a network if the network it connected to previously ?Can i use broad cast reciver for this purpose?

Upvotes: 1

Views: 5617

Answers (1)

Jibran Khan
Jibran Khan

Reputation: 3256

For receiving the Broadcast for connectivity change, you can listen like this:

Register your receiver in the AndroidManifest.xml

    <receiver
            android:name=".NetworkCheckReceiver"
            >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
   </receiver>

Then in the BroadcastReceiver class

public class NetworkCheckReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                Log.d("NetworkCheckReceiver", "NetworkCheckReceiver invoked...");


                boolean noConnectivity = intent.getBooleanExtra(
                        ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

                if (!noConnectivity) {
                    Log.d("NetworkCheckReceiver", "connected");
                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.SSID = String.format("\"%s\"", networkSSID);
                    wifiConfig.preSharedKey = String.format("\"%s\"", networkKey);
                    WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);

                    int netId = wifiManager.addNetwork(wifiConfig);
                    wifiManager.disconnect();
                    wifiManager.enableNetwork(netId, true);
                    wifiManager.reconnect();
                }
                else{
                    Log.d("NetworkCheckReceiver", "disconnected");
                }
            }
        }
 }

And of course, don't forget to add the required permissions

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

Upvotes: 1

Related Questions