Android shell get foreground app package name

adb, android, shell

Solution

This worked for me:

adb shell dumpsys window windows | grep -E 'mCurrentFocus' | cut -d '/' -f1 | sed 's/.* //g'

com.facebook.katana

Updated answer for Android Q as `mCurrentFocus` was no longer working for me:

adb shell dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1

Problem

I'm using tasker to automate the SMS sending for which I need to check if the current foreground app package name is x. If it is x then do something else do something else. I tried to use pgrep but it returns the pid even when the app x is in the background. Is there a way to check from shell if x is in foreground? Thanks

Original source

Related problems