我正在使用tasker自动发送短信,我需要检查当前的前台应用程序包名称是否为x。如果是x,则执行其他操作。我尝试使用pgrep,但即使应用程序x在后台,它也会返回pid。如果x在前台,有没有办法从shell中检查?谢谢
发布于 2015-02-18 07:41:30
这对我很有效:
adb shell dumpsys window windows | grep -E 'mCurrentFocus' | cut -d '/' -f1 | sed 's/.* //g'com.facebook.katana
更新了安卓Q的答案,因为mCurrentFocus不再适用于我:
adb shell dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1发布于 2017-07-20 22:19:04
在许多情况下,接受的答案可能会产生意想不到的结果。
某些UI元素(例如,对话框)不会在mCurrentFocus (既不是mFocusedApp)字段中显示包名称。例如,当应用程序抛出一个对话框时,mCurrentFocus通常是该对话框的标题。一些应用程序在应用程序启动时显示这些,使得这种方法无法检测应用程序是否成功带到前台。
例如,应用程序com.imo.android.imoimbeta在开始时要求输入用户国家/地区,其当前焦点是:
$ adb shell dumpsys window windows | grep mCurrentFocus
mCurrentFocus=Window{21e4cca8 u0 Choose a country}在这种情况下,mFocusedApp为空,因此要知道是哪个应用程序包名称创建了此对话框,唯一的方法是检查其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 根据用例的不同,接受的解决方案可能就足够了,但值得一提的是它的局限性。
到目前为止,我发现了一个有效的解决方案:
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
endhttps://stackoverflow.com/questions/28543776
复制相似问题