gpt4 book ai didi

android - 打开特定应用程序时启动/停止计时器

转载 作者:行者123 更新时间:2023-11-29 21:20:13 26 4
gpt4 key购买 nike

我想知道是否有任何方法可以用来查明选定的应用程序何时打开/关闭。例如,当此应用程序在后台运行时,如果打开了 Facebook,则会将其返回给应用程序并启动计时器。任何帮助将不胜感激!

最佳答案

解决此问题的一种方法是通过使用 RunningAppProcessInfo#importance 验证正在运行的进程列表并检查它们的重要性级别,重要性级别可以是从前台进程到空进程的任何位置。 .

大家感兴趣的当然是前台进程了。引用 documentation :

Foreground process

A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:

It hosts an Activity that the user is interacting with (the Activity's onResume() method has been called).

It hosts a Service that's bound to the activity that the user is interacting with. It hosts a Service that's running "in the foreground"—the service has called startForeground().

It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).

It hosts a BroadcastReceiver that's executing its onReceive() method.

Generally, only a few foreground processes exist at any given time. They are killed only as a last resort—if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.

问题是,如果它属于最后两个类别之一(ServiceBroadcastReceiver),则可能会出现一些误报。但我相信,这是你可以得到的更接近。您可以通过额外检查 the importanceReasonCode field 来消除这些误报.

另一个挑战是知道何时检查此信息。轮询是一个坏主意,因为您会耗尽大量电池电量,但如果您仅在较短/特定的时间范围内进行轮询,那么这是可以接受的,在此期间您将定期轮询以估计应用程序的时间一直在运行。

[编辑]

一个 fragment ,展示了如何遍历正在运行的进程并确定重要性级别,以及获取与这些进程相关的包。

  public void findRunningApps() {
ActivityManager activityManager = (ActivityManager)
context.getSystemService(Activity.ACTIVITY_SERVICE);

for (RunningAppProcessInfo processInfo : activityManager.getRunningAppProcesses()) {
if(processInfo.importance == IMPORTANCE_FOREGROUND) {
for (String packageName : processInfo.pkgList) {

}
}
}
}

关于android - 打开特定应用程序时启动/停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20819726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com