[android] How to turn off Wifi via ADB?

Im automating a testing procedure for wifi calling and I was wondering is there a way to turn off/on wifi via adb?

I would either like to disable/enable wifi or kill wifi calling (com.movial.wificall) and restart it.

Is it possible to do this all via adb and shell commands?

so far I have found:

android.net.wifi.WifiManager
setWifiEnabled(true/false)

Im just not sure how to put it together

This question is related to android shell adb android-wifi

The answer is


Using "svc" through ADB (rooted required):

Enable:

adb shell su -c 'svc wifi enable'

Disable:

adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.


All these input keyevent combinations are SO android/hardware dependent, it's a pain.

However, I finally found the combination for my old android 4.1 device :

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell "input keyevent KEYCODE_DPAD_LEFT;input keyevent KEYCODE_DPAD_RIGHT;input keyevent KEYCODE_DPAD_CENTER"

I tested this command:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 19 && adb shell input keyevent 19 && adb shell input keyevent 23

and only works on window's prompt, maybe because of some driver

The adb shell svc wifi enable|disable solution only works with root permissions.


use with quotes

ex: adb shell "svc wifi enable"

this will work :)


I was searching for the same to turn bluetooth on/off, and I found this:

adb shell svc wifi enable|disable

  1. go to location android/android-sdk/platform-tools
  2. shift+right click
  3. open cmd here and type the following commands

    1. adb shell
    2. su
    3. svc wifi enable/disable
  4. done!!!!!


Simple way to switch wifi on non-rooted devices is to use simple app:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        try {
            wfm.setWifiEnabled(Boolean.parseBoolean(getIntent().getStringExtra("wifi")));
        } catch (Exception e) {
        }
        System.exit(0);
    }
}

AndroidManifest.xml:

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

ADB commands:

$ adb shell am start -n org.mytools.config/.MainActivity -e wifi true
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi false

ADB Connect to wifi with credentials :

You can use the following ADB command to connect to wifi and enter password as well :

adb wait-for-device shell am start -n com.android.settingstest/.wifi.WifiSettings -e WIFI 1 -e AccessPointName "enter_user_name" -e Password "enter_password"


This works as of android 7.1.1, non-rooted

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings && adb shell input keyevent 23 && adb shell input keyevent 23

This will launch the activity and then send the DPAD center keyevent. I added another DPAD center as an experiment to see if you can enable it in the same way.


The following method doesn't require root and should work anywhere (according to docs, even on Android Q+, if you keep targetSdkVersion = 28).

  1. Make a blank app.

  2. Create a ContentProvider:

    class ApiProvider : ContentProvider() {
    
        private val wifiManager: WifiManager? by lazy(LazyThreadSafetyMode.NONE) {
            requireContext().getSystemService(WIFI_SERVICE) as WifiManager?
        }
    
        private fun requireContext() = checkNotNull(context)
    
        private val matcher = UriMatcher(UriMatcher.NO_MATCH).apply {
            addURI("wifi", "enable", 0)
            addURI("wifi", "disable", 1)
        }
    
        override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
            when (matcher.match(uri)) {
                0 -> {
                    enforceAdb()
                    withClearCallingIdentity {
                        wifiManager?.isWifiEnabled = true
                    }
                }
                1 -> {
                    enforceAdb()
                    withClearCallingIdentity {
                        wifiManager?.isWifiEnabled = false
                    }
                }
            }
            return null
        }
    
        private fun enforceAdb() {
            val callingUid = Binder.getCallingUid()
            if (callingUid != 2000 && callingUid != 0) {
                throw SecurityException("Only shell or root allowed.")
            }
        }
    
        private inline fun <T> withClearCallingIdentity(block: () -> T): T {
            val token = Binder.clearCallingIdentity()
            try {
                return block()
            } finally {
                Binder.restoreCallingIdentity(token)
            }
        }
    
        override fun onCreate(): Boolean = true
    
        override fun insert(uri: Uri, values: ContentValues?): Uri? = null
    
        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
    
        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
    
        override fun getType(uri: Uri): String? = null
    }
    
  3. Declare it in AndroidManifest.xml along with necessary permission:

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    
    <application>
    
        <provider
            android:name=".ApiProvider"
            android:authorities="wifi"
            android:exported="true" />
    </application>
    
  4. Build the app and install it.

  5. Call from ADB:

    adb shell content query --uri content://wifi/enable
    adb shell content query --uri content://wifi/disable
    
  6. Make a batch script/shell function/shell alias with a short name that calls these commands.

Depending on your device you may need additional permissions.


In Android tests I'm doing so: InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi enable") InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")


I can just do:

settings put global wifi_on 0
settings put global wifi_scan_always_enabled 0

Sometimes, if done during boot (i.e. to fix bootloop such as this), it doesn't apply well and you can proceed also enabling airplane mode first:

settings put global airplane_mode_on 1
settings put global wifi_on 0
settings put global wifi_scan_always_enabled 0

Other option is to force this with:

while true; do settings put global wifi_on 0; done

Tested in Android 7 on LG G5 (SE) with (unrooted) stock mod.


adb shell "svc wifi enable"

This worked & it makes action in background without opening related option !!


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to adb

ADB server version (36) doesn't match this client (39) {Not using Genymotion} ADB device list is empty "unable to locate adb" using Android Studio Run react-native on android emulator Solving "adb server version doesn't match this client" error Adb install failure: INSTALL_CANCELED_BY_USER Session 'app': Error Installing APK Where is adb.exe in windows 10 located? How to debug in Android Studio using adb over WiFi Set adb vendor keys

Examples related to android-wifi

Adb over wireless without usb cable at all for not rooted phones Broadcast receiver for checking internet connection in android app android adb turn on wifi via adb How to turn off Wifi via ADB? How do I connect to a specific Wi-Fi network in Android programmatically? Enabling WiFi on Android Emulator Android turn On/Off WiFi HotSpot programmatically How to detect when WIFI Connection has been established in Android? How can I get Android Wifi Scan Results into a list? How do I see if Wi-Fi is connected on Android?