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

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

问题描述

我希望有一个在后台运行一个应用程序,当任何内置的应用程序(短信,联系人等)正在运行的认识。

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.

这人有经验的反应会大大AP preciated。

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

这是在code我在服务中使用,以确定当前前台应用程序,它很容易的:

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();

这需要在活动menifest额外的许可和完美的作品。

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

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

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

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