在 Android 中,如何知道应用程序已启动。我想检测启动时安装的所有应用程序,并根据应用程序的使用时间排列应用程序的优先级。有建议这样做的解决方案吗?
我知道使用广播,但是当应用程序启动时,是否有一些 Intent 从 ActivityManager 发出,以及如何在代码中检测这个 Intent?也欢迎任何其他解决方案。
最佳答案
第一部分:
如果您知道应用程序的包名称,请尝试此操作(将以下代码段放入应用程序的 onCreate 方法中):
ActivityManager am= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
那么,
boolean exit = false;
while(!exit)
{
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals("Your package name"))
{
//Do your work here
exit = true;
}
}
当您启动应用程序时,这将被放入componentInfo中。 taskInfo.get(0).topActivity 将返回前台的 Activity。因此,您可以通过使用第二个代码 fragment 比较包来知道您的应用程序已启动。
注意:将第二个代码 fragment 放入Asynctask中,以便可以在后台检查应用是否已启动.
第二部分:
要获取优先级,我认为您可以通过检查包含所有正在运行的应用程序的列表 TaskInfo 来实现。
关于java - Android如何知道应用程序已启动并根据启动时间确定应用程序优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20875099/