是否有一种原生的android方法来从服务获取对当前运行的Activity的引用?
我有一个在后台运行的服务,我想在事件发生时(在服务中)更新我当前的Activity.有没有一种简单的方法(就像我上面建议的那样)?
我希望有一个在后台运行的应用程序,它知道任何内置应用程序(消息,联系人等)何时运行.
所以我的问题是:
我应该如何在后台运行我的应用程序.
我的后台应用程序如何知道前台运行的应用程序是什么.
有经验的人的回应将不胜感激.
谷歌似乎最终关闭了获取当前前台应用程序包的所有大门.
在Lollipop更新之后,getRunningTasks(int maxNum)由于这个答案,我使用此代码从Lollipop获取前台应用程序包:
final int PROCESS_STATE_TOP = 2;
RunningAppProcessInfo currentInfo = null;
Field field = null;
try {
field = RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception ignored) {
}
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (RunningAppProcessInfo app : appList) {
if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
app.importanceReasonCode == 0 ) {
Integer state = null;
try {
state = field.getInt( app );
} catch (Exception ignored) {
}
if (state != null && state == …Run Code Online (Sandbox Code Playgroud) 我使用以下代码在变量foregroundTaskPackageName中获取前台应用程序的活动名称.它适用于4.1到4.4之间的所有操作系统版本,但在Android 5.0 Lollipop中不起作用.
任何人都可以帮助5.0 Lollipop中的变化吗?在Lollipop中 - 我为foregroundTaskPackageName获取的文本只是'Launcher3'.我正在使用Genymotion仿真器.
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0); // get
// list
// of
// running
// tasks
String foregroundTaskAppName = null;
String foregroundTaskPackageName = foregroundTaskInfo.topActivity
.getPackageName();
Run Code Online (Sandbox Code Playgroud)