【问题标题】:Android shell get foreground app package name [duplicate]Android shell获取前台应用程序包名称[重复]
【发布时间】:2015-02-16 14:37:18
【问题描述】:

我正在使用 tasker 自动发送 SMS,我需要检查当前前台应用程序包名称是否为 x。如果它是 x 然后做其他事情做其他事情。我尝试使用 pgrep,但即使应用程序 x 在后台,它也会返回 pid。有没有办法从 shell 检查 x 是否在前台? 谢谢

【问题讨论】:

  • 您尝试过使用 adb shell ps com 吗?用于过滤所有以 com.*.* 开头的前台应用
  • 这给了我不在前台的 WhatsApp 和 Viber
  • WhatsApp 和 Viber 有一个在后台运行的进程!
  • 你是否有需要检查的包名,如果这样你可以尝试如下相同的命令 adb shell ps com.your.packagename。它将返回 pid 名称用户 ID 等等。如果不是,它将是空的。
  • “前台应用包名”是“重点应用”活动stackoverflow.com/a/13212310/1778421的一部分

标签: android shell adb


【解决方案1】:

这对我有用:

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

com.facebook.katana

Android Q 的更新答案为 mCurrentFocus 不再为我工作:

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

【讨论】:

    【解决方案2】:

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

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

    例如,应用com.imo.android.imoimbeta一开始就询问用户国家,当前关注的是:

    $ adb shell dumpsys window windows | grep mCurrentFocus
      mCurrentFocus=Window{21e4cca8 u0 Choose a country}
    

    在这种情况下,mFocusedApp 为 null,因此了解该对话框源自哪个应用程序包名称的唯一方法是检查其 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
    end
    

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 2016-03-28
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      相关资源
      最近更新 更多