xiongyihui / notes

Notes
https://xiongyihui.github.io/notes/
3 stars 0 forks source link

Automate android task with adb #4

Open xiongyihui opened 7 years ago

xiongyihui commented 7 years ago

Android adb is quite powerful. It can be used to install apps, download files, emulate finger touch, capture screen and etc. Here I use it to do a task at 8 AM and 6 PM every day automatically. The task includes:

  1. turn on the screen
  2. unlock the phone
  3. open a specific app (an Android activity)
  4. click a button of the app
  5. turn off the screen
#!/bin/sh

adb shell dumpsys power | grep -i 'Display Power: state=OFF'
if [ $? -eq 0 ]; then
    echo "Screen is off. Wake up the phone"
    adb shell input keyevent KEYCODE_WAKEUP
    sleep 1
    adb shell input touchscreen swipe 930 880 930 380 #Swipe UP
    sleep 1
fi

# get current activity name
# adb shell dumpsys window windows | grep 'mCurrentFocus'

adb shell am start -n com.kdweibo.client/com.yunzhijia.checkin.activity.MobileCheckInActivity
sleep 2

# get the position of touch
# adb shell getevent -l

adb shell input tap 739 2000 

sleep 6

adb shell input keyevent POWER
danielgomezrico commented 5 years ago

It looks like KEYCOD_WAKEUP is just for sdk > 19, so take a look to this:

awake_screen() {
  androidSdkVersion="$(adb shell getprop ro.build.version.sdk)"

  if [ "androidSdkVersion" -gt 19 ]; then
    echo "Awaking android device."
    adb_all shell input keyevent 224 # KEYCODE_WAKEUP just for < Android 19
  else
    echo "Checking if its needed to turn on the screen."

    adb shell dumpsys power | grep -i 'Display Power: state=OFF'
    if [ $? -eq 0 ]; then
      echo "Screen is off. Wake up the phone"
      adb shell input keyevent 26 # KEYCODE_POWER will turn of if it is turned on
    fi
  fi
}

awake_screen