getRunningTasks() deprecated之后如何获得topActivity

在Android L之后,getRunningTasks()因隐私问题被弃用,取而代之的是通过UsageStatsManager获取应用使用情况。本文介绍了如何在不同Android版本下获取topActivity的包名,包括需要的权限和用户授权流程,并提供了一个应用锁的简单实现示例。
摘要由CSDN通过智能技术生成
前言

在Android sdk 22之前,要想获得topActivity,只需要用getRunningTasks(int maxNum)即可返回当前正在运行的任务栈,从任务栈中取出第一个即可,如下:

ActivityManager am = ((ActivityManager) getSystemService(ACTIVITY_SERVICE));
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(5);
String packageName = taskInfo.get(0).topActivity.getPackageName();

如上即可获得topActivity的包名,有了包名之后想干什么就干什么了。不过,如果就这么简单,就不值得记录学习了。

getRunningTasks() was deprecated

在Android L(也就是sdk 22)之后,getRunningTasks()方法以及被抛弃,原因是出于保护用户隐私之类的。如下:

for L we do plan to have a new solution that will address some of the existing use cases of getRecentTasks(): we hope to expose the system’s internal usage stats service in a new and expanded form that is available to third party apps through the SDK.
The new usage stats service should have two major pieces of information. First, it will provided aggregated stats of the time the user spent in each app, and the last launch time of those apps, rolled up over days, weeks, months, and years. Second, it will include detailed usage events over the last few days, describing the time and ComponentName when any activity transitions to the foreground or background.
Access to this new usage data will require that the user explicitly grant the app access to usage stats through a new settings UI. They will be able to see all apps that have access and revoke access at any point.

大概意思就是该方法以及被抛弃,然后用了一种新的更好地方式来代替,不过这种方式需要用户授予权限。这种方式就是用UsageStatsManager,详细请点击here
下面直接上代码,在Android L之后获取topActivity包名:

/**
 * 获得top activity的包名
 * @return
 */
public String getTopPackage(){
    long ts = System.currentTimeMillis();
    UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService(Context.USAGE_STATS_SERVICE);
    List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-1000, ts);
    if (usageStats == null || usageStats.size() == 0) {
  //如果为空则返回&#
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值