从后台任务或服务中确定当前的前台应用程序 [英] Determining the current foreground application from a background task or service

查看:17
本文介绍了从后台任务或服务中确定当前的前台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个在后台运行的应用程序,它知道任何内置应用程序(消息、联系人等)何时正在运行.

I wish to have one application that runs in the background, which knows when any of the built-in applications (messaging, contacts, etc) is running.

所以我的问题是:

  1. 我应该如何在后台运行我的应用程序.

  1. How I should run my application in the background.

我的后台应用程序如何知道当前在前台运行的应用程序是什么.

How my background application can know what the application currently running in the foreground is.

非常感谢有经验的人的回复.

Responses from folks with experience would be greatly appreciated.

推荐答案

关于2. 我的后台应用程序如何知道当前在前台运行的应用程序是什么."

With regards to "2. How my background application can know what the application currently running in the foreground is."

请勿使用 getRunningAppProcesses() 方法,因为根据我的经验,这会返回各种系统垃圾,您将获得多个具有 RunningAppProcessInfo.IMPORTANCE_FOREGROUND 的结果.使用 getRunningTasks() 代替

Do NOT use the getRunningAppProcesses() method as this returns all sorts of system rubbish from my experience and you'll get multiple results which have RunningAppProcessInfo.IMPORTANCE_FOREGROUND. Use getRunningTasks() instead

这是我在我的服务中用来识别当前前台应用程序的代码,非常简单:

This is the code I use in my service to identify the current foreground application, its really easy:

ActivityManager am = (ActivityManager) AppService.this.getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

就是这样,然后您就可以轻松访问前台应用程序/活动的详细信息:

Thats it, then you can easily access details of the foreground app/activity:

String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
PackageManager pm = AppService.this.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

这需要在活动清单中获得额外许可并且完美运行.

This requires an additional permission in activity menifest and works perfectly.

<uses-permission android:name="android.permission.GET_TASKS" />

这篇关于从后台任务或服务中确定当前的前台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆