Last Updated: February 25, 2016
·
2.24K
· ferdy182

Change the wifi state to test connection loss without leaving the activity

How to change the wifi state to test connection loss in Android without leaving the activity (that would produce onPause and onStop events)

First, create a broadcast receiver who will receive an intent you will send. This receiver will change the wifi state

public class ChangeWifiState extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        WifiManager wfm = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);          wfm.setWifiEnabled(Boolean.parseBoolean(intent.getStringExtra("wifi")));
    }
}

This receiver reads a boolean from the intent extras that says if the wifi should be enabled or disabled.

Then declare it in your manifest. It can be in the same app or in another app you install on the phone

<receiver android:name="ChangeWifiState" android:exported="true" >
    <intent-filter>
        <action android:name="WifiChange" />
    </intent-filter>
</receiver>

The receiver should have the attribute exported to true in the latter case, so it can be triggered from anywhere. It also has an intent filter we will use as our intent action to fire it.

Also add a permission in the AndroidManifest.xml to change the wifi state
<uses-permission android:name="android.permission.CHANGEWIFISTATE" />
(that's why you probably prefer to use a different app as your wifi switcher)

That's it, now you can open a terminal an write this command to send a BroadcastIntent that will be catched by the receiver we have declared and it will change the wifi state, so the system will fire a CONNECTIVITY_CHANGE broadcast intent and you will be able to see if your application handles a connectivity change correctly

adb shell am broadcast -a WifiChange -c android.intent.category.DEFAULT
-n com.your.app/.ChangeWifiState -e wifi [boolean]

where [boolean] can be true/false