68

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

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Nefariis
  • 3,451
  • 10
  • 34
  • 52

13 Answers13

108

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.

Community
  • 1
  • 1
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
  • 1
    Thank you very much for the post. Its not quite the same on my phone, but since you posted the input events I figured out it is key events 19 and 23. Thanks Again. : ) – Nefariis Apr 10 '12 at 15:56
  • 1
    Ok you got it? Yeah I tested that on a Droid X, I wasn't sure what phone you had :) – Jared Burrows Apr 10 '12 at 16:21
  • In my opinion answer by Berkk is much better (notably less hacky). – karni Apr 11 '13 at 19:44
  • 2
    to use those keyevents to toggle wifi in Android 5.0 you would probably have to hit different events then in answer. I would say `adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 23` (the first one can be 20 as well) - this is working if there is no option selected when you enter the wifi settings screen (if there is, you should skip the first event) – Bartek Lipinski Jan 22 '15 at 23:55
  • 1
    I answered this over 2 years ago. It was just an example to help someone automate a task. – Jared Burrows Jan 23 '15 at 00:36
  • adb shell svc wifi enable/disable. Also just realised there where several comments about this in Berkk's answer, my bad. – McP Apr 13 '15 at 23:14
  • 1
    svc wifi enable/disable works only for rooted devices. The other way of automating by using keyevent won't work across all androids. – Thejus Krishna Sep 04 '15 at 10:46
  • @ThejusKrishna See the date above. I posted this answer over 3 years ago with minor edits. If you want to make an edit you can. Please learn how to use Stack Overflow. – Jared Burrows Sep 06 '15 at 15:34
  • Please don't feel offended. This answer makes no sense across all the android phones. Better answer was found below and definitely feel this is outdated. – Thejus Krishna Sep 07 '15 at 05:48
  • 2
    it required `su` here like @IvanMorgillo said `adb shell su -c 'svc wifi disable'` – Aquarius Power Feb 18 '16 at 02:24
  • i tried to disable the wifi and got: `sh: resetreason: can't execute: Permission denied` how should i get permissions? the phone wasn't locked either – ThunderWiring Apr 19 '17 at 20:45
  • Doesn't work on my device. I have full root. No errors, no output. Network stays connected, no change in the device settings still shows wifi on and connected. – Jeffrey Blattman Mar 04 '22 at 01:52
  • These commands: adb shell "su 0 svc wifi enable" / adb shell "su 0 svc wifi disable to enable/disable wifi respectively worked for me – Red M Oct 25 '22 at 15:48
76

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

adb shell svc wifi enable|disable
apaderno
  • 28,547
  • 16
  • 75
  • 90
Berkk
  • 785
  • 1
  • 5
  • 3
  • 3
    I've tried using this code on 6 different devices ranging from Gingerbread to JellyBean, rooted to non-rooted and I couldn't get it to work on any of them. What devices are you able to get this to work on? – Nefariis Sep 11 '12 at 21:44
  • 6
    @Nefarii - for this I needed to request adb shell into the device.....then request su permission....then I was able to run these commands properly. – dell116 Oct 18 '12 at 20:47
  • Works on rooted Sony Ericsson Xperia and Motorola Razr – Ari Sep 20 '13 at 13:18
  • 5
    Working on rooted Nexus 5, 4.4.2: adb shell su -c "svc wifi disable" – Ivan Morgillo May 20 '14 at 09:22
  • 1
    this works on my Samsung S8 non-rooted, the `adb shell su -c 'svc wifi enable'` didn't (since it wasn't rooted) – trevren11 Jun 15 '18 at 16:49
  • Works on a non-rooted Pixel 4a with Android 11. ( Attached via USB, Developer mode on). – treesAreEverywhere Dec 16 '20 at 01:32
  • Works on Samsung Galaxy S20 Ultra running non-rooted stock Android 11 image – CCJ May 05 '21 at 19:05
  • Works on a Zebra TC26 device - Android 10 (non rooted) – NourB Jan 03 '23 at 09:27
26

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
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Ruslan
  • 1,076
  • 10
  • 10
10

Via cmd command on Android 11 & 12 (no-root-required)

enable Wi-Fi (turn on):

adb shell cmd -w wifi set-wifi-enabled enabled 

disable Wi-Fi (turn off):

adb shell cmd -w wifi set-wifi-enabled disabled
wuseman
  • 1,259
  • 12
  • 20
  • the command returns the `Invalid args for set-wifi-enabled: java.lang.IllegalArgumentException: Expected 'enabled' or 'disabled' as next arg but got 'disable'`/ [...] `but got 'enable'` error if running `enable` / `disable` instead of `enabled` / `disabled`. – user598527 May 14 '22 at 08:09
  • 1
    Thank you for correcting this. Will fix it on my wiki immediately as well. – wuseman May 15 '22 at 05:25
  • 1
    cool, works perfectly for me! (Galaxy Tab A7, Android 11) – miva2 Feb 15 '23 at 10:00
7
  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!!!!!

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
Musab
  • 1,067
  • 12
  • 12
5

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.

SebMa
  • 4,037
  • 29
  • 39
Igor Romcy
  • 336
  • 4
  • 7
  • This was particularly useful: my Genymotion emulators randomly start up with the wifi available but sometimes not selected. I used this: shell 'am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings; input keyevent 20; input keyevent 23' – android.weasel Dec 08 '16 at 15:16
3

It will work if you use with quotes:

adb shell "svc wifi enable"
Dharman
  • 30,962
  • 25
  • 85
  • 135
SanalBathery
  • 628
  • 5
  • 10
2

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.

Treviño
  • 2,999
  • 3
  • 28
  • 23
1

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"
SebMa
  • 4,037
  • 29
  • 39
1

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.

Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124
0

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.

Adam Deane
  • 23
  • 5
0

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"

0

In Android tests I'm doing as follows:

InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi **enable**")
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi **disable**")
user598527
  • 175
  • 13