I need to run some automated tests on an android device, the problem is that the screen needs to be unlocked first. I have tried:
input keyevent KEYCODE_MENU
But this hasn't worked.
I have access to a rooted device for this purpose and have removed the password. Just need a way to unlock the screen.
If you set your lock screen to none, you just need to send a power on command using adb.
# Switches on the android devices screen if it isn’t already on.
if `adb shell dumpsys input_method | grep mInteractive`.include? 'false'
`adb shell input keyevent KEYCODE_POWER`
end
# Pre lollipop devices respond to this command a bit differently.
if `adb shell dumpsys input_method | grep mScreenOn`.include? 'false'
`adb shell input keyevent KEYCODE_POWER`
end
The above will press the power button if the screen isn't already on.
Related
I have an android phone on which I want to programatically toggle airplane mode.
I've been unable to root this device, which has prevented any apps I'm running from having permission to edit these settings, so am using adb to open the settings menu and toggle the switch there.
Executing the following adb shell commands will work in some cases:
//Get airplane mode settings menu
adb -s ${device} shell am start -a android.settings.AIRPLANE_MODE_SETTINGS
//Hit enter (as many times as required)
adb -s ${device} shell input keyevent KEYCODE_ENTER
//Check the state of airplane mode to determine when successful
adb -s ${device} shell settings get global airplane_mode_on
However, this only work if the menu containing the airplane mode switch is the first menu option listed on the settings page, since "android.settings.AIRPLANE_MODE_SETTINGS" will only navigate to the menu where the setting is found. It will not perform any focussing on the setting itself, so the following command to hit enter will press the wrong setting.
If using this approach, is there a way to identify/focus only the airplane toggle switch, or otherwise check which menu item is in focus so the items can be iterated until the correct one is found?
Additionally, it would be great if there was a way to execute these adb commands without requiring the phone to be plugged into a PC - i.e. can the adb client be run on the phone itself (and then trick itself into thinking it is a connected device).
And finally - the end goal here is simply to toggle airplane mode programatically on demand (ultimately the request will be triggered by a node.js process running in termux app). If there is a better way to achieve this without using adb that doesn't require root permissions, this would also work.
Here are the ADB commands to turn on and turn of airplane mode:
Turn on:
adb shell settings put global airplane_mode_on 1
adb shell am broadcast -a android.intent.action.AIRPLANE_MODE
Turn off:
adb shell settings put global airplane_mode_on 0
adb shell am broadcast -a android.intent.action.AIRPLANE_MODE
I suspect this is an incredibly niche requirement, but if anyone is interested in how to toggle airplane mode on a non-rooted android phone using adb commands, where the UI airplane mode toggle button is not the first item in the settings activity.... read below!
As previously mentioned, load the screen containing the airplane mode button:
adb shell am start -a android.settings.AIRPLANE_MODE_SETTINGS
Now to check the current state of the UI:
adb shell uiautomator dump
adb pull /sdcard/window_dump.xml
STDOUT of the first command above can be checked to determine exactly where the uiautomator dump is sent by default.
To navigate the settings menu, use the DPAD UP/DOWN keyevents:
adb shell input keyevent KEYCODE_DPAD_DOWN
adb shell input keyevent KEYCODE_DPAD_UP
Depending on the device, I've found that using the above options either results in nodes being selected or focused. The output of the UI dump can be parsed, and in the DOM search for either "node[selected=true]" or "node[focused=true]" depending on which the device uses. I'm eventually checking to see when node.attr('text').toUpperCase.contains('PLANE MODE') to check when the airplane mode setting has been reached, and then finally executing:
adb shell input keyevent KEYCODE_ENTER
to activate the switch.
For now this covers the devices I've tried it on, but performance is not great if there is a lot of scrolling in the menu to do. I'd be interested to know if there's a way to hold uiautomator dump output in memory on the device and parse the XML there to avoid unnecessary I/O of outputting to a file, pulling to a local drive and reading it back into memory there.
Create bat file:
adb -s 3e31d8d97d95 shell am start -a android.settings.AIRPLANE_MODE_SETTINGS ; while [ 0 -le 5 ]; do input keyevent 23; sleep 0.1;input keyevent 23;sleep 13; echo 'done'; done;
Make sure the "stay awake" is ON in debug menu.
Also make sure this is more "gray" - focues:
Run the script.
if [[ "$(adb shell dumpsys wifi | grep mAirplaneModeOn)" == "mAirplaneModeOn false" ]]; then
adb shell am start -a android.settings.AIRPLANE_MODE_SETTINGS
&& input keyevent 19
&& input keyevent 23
&& input keyevent 4
fi
When build and run iOS app using Xcode, the phone becomes awake and app runs. Is there a way to wake and unlock Android phone (or tablet) screen then run installed Android app (Eclipse, Android Studio)?
One solution: set the following flags in your activity class(es):
if (BuildConfig.DEBUG) {
// These flags cause the device screen to turn on (and bypass screen guard if possible) when launching.
// This makes it easy for developers to test the app launch without needing to turn on the device
// each time and without needing to enable the "Stay awake" option.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
These flags will:
Turn on the screen
Bypass the lock-screen
Allow showing the activity even if the device is locked
By setting those flags in your base activity, you'll be able to continue using your application even if the device was off and/or locked at the time of running. If you try to leave your application's process (i.e., hitting the home button, or switching to another app), the lock screen will appear, and you'll have to manually unlock to continue using the device.
Warning: this should only be used while developing/debugging your application, so I recommend keeping the if (BuildConfig.DEBUG) check, as it is in this example
Better and easiest solution is use the option (in development section) that the screen never goes off I thing the name is "Stay awake". This option prevent your phone to get locked when the usb cable is connected.
Another way is to write a script which runs before the app deploys and unlocks the device. This requires no app code change and will not change screen timeout which can have security implications.
You can find the full setup here
#!/bin/bash
# When a device is attached there will be atleast 3 lines -> heading, device details, an empty new line
if adb devices | wc -l | grep "3"; then
# Check if device locked, this may differ on some OEMs
if adb shell dumpsys window | grep "mInputRestricted=true"; then
echo "Device is Locked"
adb shell input keyevent KEYCODE_WAKEUP # wakeup device
adb shell input touchscreen swipe 530 1420 530 1120 # swipe up gesture
adb shell input text "000000" # <- Change to the your device PIN/Password
#adb shell input keyevent 66 # simulate press enter, if your keyguard requires it
else
echo "Device already unLocked"
fi
# 2 = Stay awake on USB, 0 = reset
adb shell settings put global stay_on_while_plugged_in 2
#adb shell settings put system screen_brightness 700
adb shell input keyevent KEYCODE_WAKEUP
adb shell input touchscreen tap 0 0 # this will wake up the screen and won't have any unwanted touches
else
echo "There should be only one device connected at a time"
fi
return 0
You cant unlock and wake the phone as that would not be very secure, however you can enable "Stay awake" in developer options.
How to wake up Android with use adb - I want to wake up (if asleep) Android terminal before debugging every new version of application.
Typical flow is:
1. I do some changes in Eclipse.
2. In the meantime screen goes off or not.
3. I run "debug" and want force screen to wake up.
I found a method with "power key" emulation but it does not turn it on but rather toggles the power state. I do not want to add extra code to my application. What are the other methods to do such trivial task, please help.
adb shell input keyevent KEYCODE_WAKEUP
As described here, this wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake.
To toggle sleep/wake with one command you can issue
adb shell input keyevent KEYCODE_POWER
Just use :
adb shell input keyevent 26
Here's what I came up with:
adb shell dumpsys power | grep "mScreenOn=true" | xargs -0 test -z && adb shell input keyevent 26
This will first check to see if the screen is on. If it isn't, it will emulate the power key, which will turn on the device's screen.
if you execute
adb shell input keyevent KEYCODE_POWER and got Killed, you should use root user by execute su before.
sleep:(adb shell) input keyevent KEYCODE_SLEEP
wakeup:(adb shell) input keyevent KEYCODE_WAKEUP
toggle:(adb shell) input keyevent KEYCODE_POWER
You can check device's current power state (including display) via adb with dumpsys power command and send the power key press event only if the display is off. The easier solution would be disabling the display timeout altogether "while connected to USB" in the Developer options.
you could also add the following flags to your onCreate() in your main activity:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
This way your device should wake up when it is loaded onto the device through Eclipse.
I know that this is the opposite of what the OP requested, but I wanted to point out the definition of "truly asleep" for other readers:
If adb is active, then the device is not truly asleep, since USB is on and the command prompt is running (how else is adb shell going to work?). When fully asleep, only the physical power button will wake it (unless other buttons are selected as a wake source in the BSP). My project draws about 120ma with screen off, but only 23ma in sleep mode (disconnect USB cable). "adb shell input keyevent 26" does not work in this mode. Neither does the serial console.
My test fixture does have access to the battery and external power line separately. I can toggle the power line (with battery connected) to wake it up. I also have a switched USB hub that disconnects the USB specifically for the sleep portion of the test.
I hope this can be some help to someone.
For Windows and Eclipse you can use .bat file:
#ECHO OFF
setlocal
for /f "delims= tokens=1*" %%a in ('adb shell dumpsys power ^| findstr.exe "mScreenOn="') DO (
for /f "delims== tokens=2*" %%S in ("%%a") do (
if "%%S" == "false" (goto move1) else (goto move2)
)
)
:move1
adb shell input keyevent 26
goto end
:move2
goto end
:end
exit
It will check, if screen is off it will switch the power state.
To use it with Eclipse this .bat file should be used as "External tool" (just fill the path to the .bat) and linked to the project in it's properties (Builders - Import - ).
I used the following to wake up remote devices for automated tests. If the screen isn't on, then it will press the power button followed by the menu button.
(
cd ${platform-tools};
./adb shell dumpsys power | grep -i 'SCREEN_ON' >/dev/null;
if [ $? -eq 0 ]; then
echo "Screen is on...";
else
echo "Pressing buttons to wake-up...";
# http://developer.android.com/reference/android/view/KeyEvent.html
./adb shell input keyevent 26; # Power
./adb shell input keyevent 82; # Menu
echo "Pausing for state to settle...";
sleep 1;
./adb shell dumpsys power | grep -i 'SCREEN_ON';
fi;
echo '---';
./adb shell dumpsys power | grep -i 'SCREEN'
)
How can I turn the sceen on ?
I tried something like this
adb -d shell am broadcast -a android.intent.action.SCREEN_ON
It really should work, I send broadcast intent it is received by the system, but the screen doesn't turn on
I do not understand what is the problem, is it possible to turn the screen of the device by code ? I mean with software ? Cause it seems like the turning on of the screen is done just by the hardware button press . . . at least I got that felling , am I wrong ?
adb shell input keyevent KEYCODE_POWER
Works to turn on screen (when display is off)
Works to turn off screen (when display is on/awake)
For Android 5.0 and above:
adb shell input keyevent KEYCODE_WAKEUP
or
adb shell input keyevent 224
KEYCODE_WAKEUP
Key code constant: Wakeup key. Wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake.
https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_WAKEUP
Note: KEYCODE_POWER has been added in API level 1, while KEYCODE_WAKEUP has been added in API level 20!
u can turn it on/off if u do like:
adb shell
#shell: input keyevent 26
#shell: (enter or via hidden command empty line)
#shell: exit
this worked for me on some android versions ;)(NOTE: this will turn the screen on and off, depends on the actual screen state)
To detect the current state of the screen u can use the following ways:Android < 5.x.xadb shell dumpsys input_methodIn the output search for mScreenOn=true/false
Android >= 5.x.xadb shell dumpsys displayIn the output search for mScreenState=ON/OFF
In my scripts i use this \s{0,}mScreen(State|On)=(?<STATE>(true|false|on|off))\s{0,} (Compiled|IgnoreCase|ExplicitCapture) regular expression for both outputs to detect the current state.
EDIT (16.03.2018):
There is also another way to detect the screen state, it works since Android 3.0. The dumpsys window policy command will give us all we need. - In the output search for mScreenOn(Fully)?=(?<STATE>(true|false)).
There are also other useful informations like:
mUnrestrictedScreen (value is like: (0,0) 768x1280)
mRestrictedScreen (value is like: (0,0) 768x1184)
Regards,
k1ll3r8e
I could be wrong about this, but...
You shouldn't think of broadcasts as something to send to get things done, but instead think of them as things that are sent when things are done.
I think the system sends 'android.intent.action.SCREEN_ON' when screen is goes on, but sending 'android.intent.action.SCREEN_ON' does not necessarily make the screen go on.
I hope this makes sense.
For the answer, you can find it in...
Calling hidden API in android to turn screen off
turn the screen on/off in Android with a shake
The command to toggle the screen on/off is:
adb shell input keyevent 26
This condensed command is preferred because it allows you to use it in scripts.
Cheers!
this works in android 12
#!/bin/bash
screenState=$(adb shell dumpsys window policy | grep screenState=SCREEN_STATE_ | cut -c 32-)
if [ "$screenState" == "OFF" ]; then
adb shell input keyevent KEYCODE_POWER
fi
How do I use adb to perform some automated tasks on my android phone? I need to find commands that I can issue from the command line (ideally, using a .bat file) that will be capable of more than simply opening an application or sending an input keyevent (button press).
For instance, I want to toggle Airplane Mode on or off from the command line. Currently, the best I can do is launch the Wireless & network settings menu and then use input keyevents to click Airplane mode:
adb shell am start -a android.settings.AIRPLANE_MODE_SETTINGS
adb shell input keyevent 19 & adb shell input keyevent 23
There are quite a few drawbacks to this method, primarily that the screen has to be on and unlocked. Also, the tasks I want to do are much broader than this simple example. Other things I'd like to do if possible:
1.Play an mp3 and set it on repeat. Current solution:
adb shell am start -n com.android.music/.MusicBrowserActivity
adb shell input keyevent 84
adb shell input keyevent 56 & adb shell input keyevent 66 & adb shell input keyevent 67 & adb shell input keyevent 19
adb shell input keyevent 23 & adb shell input keyevent 21
adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 22 & adb shell input keyevent 22 & adb shell input keyevent 23 & adb shell input keyevent 23
2.Play a video. (current solution: open MediaGallery, send keyevents, similar to above)
3.Change the volume (current solution: send volume-up button keyevents)
4.Change the display timeout (current solution: open sound & display settings, send keyevents)
As before, these all require the screen to be on and unlocked. The other major drawback to using keyevents is if the UI of the application is changed, the keyevents will no longer perform the correct function. If there is no easier way to do these sort of things, is there at least a way to turn the screen on (using adb) when it is off? Or to have keyevents still work when the screen is off?
I'm not very familiar with java. That said, I've seen code like the following (source: http://yenliangl.blogspot.com/2009/12/toggle-airplane-mode.html) to change a setting on the phone:
Settings.System.putInt(Settings.System.AIRPLANE_MODE_ON, 1 /* 1 or 0 */);
How do I translate something like the above into an adb shell command? Is this possible, or the wrong way to think about it?
I can provide more details if needed. Thanks!
Although question is old, it might help someone else.
For video playback, you can try this:
adb shell am start -a android.intent.action.VIEW -d "file:///mnt/sdcard/DCIM/Camera/test.3gp" -t "video/*"
^gives you a prompt of all capable players that can play this file.
adb shell am start -a android.intent.action.VIEW -d "file:///mnt/sdcard/DCIM/Camera/test.3gp" -t "video/*" -n "com.alensw.PicFolder/.PlayerActivity"
^plays in player specified by switch -n.
I'm working on the same set of issues. (I mostly solved the context issue with straight button presses by using the keyevent HOME and then MENU, but -- somehow -- even that's unreliable.) I'm currently investigating SL4A (Scripting Layer for Android), which has promise. It allows Perl, Python, Lua, and other scripting languages to interact with the Android API from your PC after starting an SL4A server on the device -- which can also be done from the PC. I'm finding "Pro Android Python with SL4A" to be an excellent resource; I would have saved myself days of trial-and-error and hunting on the Web if I had started with that book
The Java example you show is for a program that is running on the phone itself. You might be able to program some kind of an interpreter on the phone that handles adb commands. That way you are not dependent anymore on keyevents. This is not a minor undertaking, however.
MonkeyRunner also looks like it has promise, though I haven't dug deep enough to find its limits yet.
Android ScreenCast lets you view and control your device's screen from your PC, which also has potential for automation. It does have present some logistical issues for that application, though.
By the way, you can get past the locked homescreen with a MENU keyevent and a set of sendevents (in place of keyevents).