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
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
The accepted answer might give unexpected results in many cases.
Some UI elements (e.g., dialogs) will not show the package name on the mCurrentFocus
(neither mFocusedApp) field. For example, when an app throws a dialog, the mCurrentFocus
is often the dialog's title. Some apps show these on app start, making this approach unusable to detect if an app was successfully brought on foreground.
For example, the app com.imo.android.imoimbeta
asks for the user country at start, and its current focus is:
$ adb shell dumpsys window windows | grep mCurrentFocus
mCurrentFocus=Window{21e4cca8 u0 Choose a country}
The mFocusedApp
is null in this case, so the only way to know which app package name originated this dialog is by checking its mOwnerUID
:
Window #3 Window{21d12418 u0 Choose a country}:
mDisplayId=0 mSession=Session{21cb88b8 5876:u0a10071} mClient=android.os.BinderProxy@21c32160
mOwnerUid=10071 mShowToOwnerOnly=true package=com.imo.android.imoimbeta appop=NONE
Depending on the use case the accepted solution might suffice but its worth mentioning its limitations.
A solution that i found to work so far:
window_output = %x(adb shell dumpsys window windows)
windows = Hash.new
app_window = nil
window_output.each_line do |line|
case line
#matches the mCurrentFocus, so we can check the actual owner
when /Window #\d+[^{]+({[^}]+})/ #New window
app_window=$1
#owner of the current window
when /mOwnerUid=[\d]+\s[^\s]+\spackage=([^\s]+)/
app_package=$1
#Lets store the respective app_package
windows[app_window] = app_package
when /mCurrentFocus=[^{]+({[^}]+})/
app_focus=$1
puts "Current Focus package name: #{windows[app_focus]}"
break
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With