前言
在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) {
//如果为空则返回&#