1. 程式人生 > >android 獲取當前正在使用的程式名和activity類名

android 獲取當前正在使用的程式名和activity類名

需要用到ActivityManager. getRunningTasks(int maxNum)

API介紹說:

Return a list of the tasks that are currently running, with the most recent being first and older ones after in order.  Note that "running" does not mean any of the task's code is currently loaded or activity -- the task may have been frozen by the system, so that it can be restarted in its previous state when next brought to the foreground.

maxNum          The maximum number of entries to return in the list.  The actual number returned may be smaller, depending on how many tasks the user has started.

當我們把1傳遞給maxNum時,返回的就是當前執行的那個TASK,然後就可以從task中獲取最頂層的activity,此activity就是當前顯示給使用者那個activity

new Thread() {


@Override
public void run(){

while(true) {
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
ComponentName cn = am.getRunningTasks(1).get(0).topActivity; 
System.out.println("當前的使用的包名pkg:"+cn.getPackageName()); 
System.out.println("當前的使用的activity類名:"+cn.getClassName());

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}.start();