如何在android中获取当前的前台活动上下文? [英] How to get current foreground activity context in android?

查看:41
本文介绍了如何在android中获取当前的前台活动上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我的广播被执行时,我都想对前台活动显示警报.

Whenever my broadcast is executed I want to show alert to foreground activity.

推荐答案

知道ActivityManager管理Activity,所以我们可以从ActivityManager获取信息>.我们通过

Knowing that ActivityManager manages Activity, so we can gain information from ActivityManager. We get the current foreground running Activity by

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

更新 2018/10/03
getRunningTasks() 已弃用.请参阅下面的解决方案.

UPDATE 2018/10/03
getRunningTasks() is DEPRECATED. see the solutions below.

此方法已在 API 级别 21 中弃用.从 Build.VERSION_CODES.LOLLIPOP 开始,此方法不再适用于第三方应用程序:引入以文档为中心的最近记录意味着它可以将个人信息泄露给调用者.为了向后兼容,它仍将返回其数据的一小部分:至少是调用者自己的任务,可能还有一些其他任务,例如已知不敏感的 home.

This method was deprecated in API level 21. As of Build.VERSION_CODES.LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.

这篇关于如何在android中获取当前的前台活动上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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