Android基础总结之二:检测Activity是否在当前Task栈顶

时间:2023-01-07 02:20:52

文章出处:http://blog.csdn.net/shift_wwx

Android系统内部状态信息的相关api:

得到ActivityManager :

ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE)


这个位查到底是什么信息:

ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); 


获取进程内存状态的信息:

Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(processIds);


获取当前运行的service信息:

List<RunningServiceInfo> runningServiceInfos = activityManager.getRunningServices(MaxValue); 


获取当前运行的任务信息:

List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(MaxValue);


其中runningTaskInfos 的 topActivity就是当前Task的活跃Activity
在getRunningTasks()所返回的Task队列中系统会根据这些Task的活跃度有一个排序,越活跃越是靠前。第一个就是当前活动的Task

/**
* 检测某ActivityUpdate是否在当前Task的栈顶
*/

public boolean isTopActivy(String cmdName){
ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
String cmpNameTemp = null;
if(null != runningTaskInfos){
cmpNameTemp=(runningTaskInfos.get(0).topActivity).toString(); //这里cmpNameTemp是package name/class name
Log.e("cmpNameTemp","cmpNameTemp:"+cmpNameTemp);
}
if(null == cmpNameTemp)
return false;
return cmpNameTemp.contains(cmdName); //如果cmdName是package name得用contains,但是cmdName是package name/class name,则用equals
}

最后在应用中添加所需的权限:

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