May 6, 2013

检测Activity是否在当前Task的栈顶

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);
                Log.e("cmpname","cmpname:"+cmpName);
        }

       if(null == cmpNameTemp)return false;
       return cmpNameTemp.equals(cmdName);
}


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

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