首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android shell获取前台应用包名称

Android shell获取前台应用包名称
EN

Stack Overflow用户
提问于 2015-02-16 22:37:18
回答 2查看 15K关注 0票数 10

我正在使用tasker自动发送短信,我需要检查当前的前台应用程序包名称是否为x。如果是x,则执行其他操作。我尝试使用pgrep,但即使应用程序x在后台,它也会返回pid。如果x在前台,有没有办法从shell中检查?谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-18 07:41:30

这对我很有效:

代码语言:javascript
复制
adb shell dumpsys window windows | grep -E 'mCurrentFocus' | cut -d '/' -f1 | sed 's/.* //g'

com.facebook.katana

更新了安卓Q的答案,因为mCurrentFocus不再适用于我:

代码语言:javascript
复制
adb shell dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1
票数 23
EN

Stack Overflow用户

发布于 2017-07-20 22:19:04

在许多情况下,接受的答案可能会产生意想不到的结果。

某些UI元素(例如,对话框)不会在mCurrentFocus (既不是mFocusedApp)字段中显示包名称。例如,当应用程序抛出一个对话框时,mCurrentFocus通常是该对话框的标题。一些应用程序在应用程序启动时显示这些,使得这种方法无法检测应用程序是否成功带到前台。

例如,应用程序com.imo.android.imoimbeta在开始时要求输入用户国家/地区,其当前焦点是:

代码语言:javascript
复制
$ adb shell dumpsys window windows | grep mCurrentFocus
  mCurrentFocus=Window{21e4cca8 u0 Choose a country}

在这种情况下,mFocusedApp为空,因此要知道是哪个应用程序包名称创建了此对话框,唯一的方法是检查其mOwnerUID

代码语言:javascript
复制
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 

根据用例的不同,接受的解决方案可能就足够了,但值得一提的是它的局限性。

到目前为止,我发现了一个有效的解决方案:

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28543776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档