2010-03-18 14 views

Répondre

2

Vous pouvez référencer le projet "DevTools".

En utilisant ActivityManager vous pouvez obtenir des informations de lots, tels que ActivityManager.RunningAppProcessInfo, ActivityManager.RunningTaskInfo, ...

Mais je ne suis pas sûr le résultat sera identique à la commande « top ».

voir ActivityManager

+7

Aucune utilisation du processeur ou des informations de temps peuvent être trouvés là (ou l'ai-je manqué?), seulement l'utilisation de mémoire parmi d'autres choses. – yuku

+0

pour l'utilisation du processeur, vous pouvez vous référer à CPUGauge.cpp, je pense qu'il n'y a pas "API publique" pour ce genre d'informations que vous voulez. Ou vous devez analyser "/ proc/stat" par vous-même. –

+0

Pour référence, voici la source de CPUGauge https://android.googlesource.com/platform/frameworks/native/+/a6938ba/libs/surfaceflinger/CPUGauge.cpp –

25

Pour l'utilisation du processeur complet (pas pour chaque processus), vous pouvez utiliser:

/** 
* 
* @return integer Array with 4 elements: user, system, idle and other cpu 
*   usage in percentage. 
*/ 
private int[] getCpuUsageStatistic() { 

    String tempString = executeTop(); 

    tempString = tempString.replaceAll(",", ""); 
    tempString = tempString.replaceAll("User", ""); 
    tempString = tempString.replaceAll("System", ""); 
    tempString = tempString.replaceAll("IOW", ""); 
    tempString = tempString.replaceAll("IRQ", ""); 
    tempString = tempString.replaceAll("%", ""); 
    for (int i = 0; i < 10; i++) { 
     tempString = tempString.replaceAll(" ", " "); 
    } 
    tempString = tempString.trim(); 
    String[] myString = tempString.split(" "); 
    int[] cpuUsageAsInt = new int[myString.length]; 
    for (int i = 0; i < myString.length; i++) { 
     myString[i] = myString[i].trim(); 
     cpuUsageAsInt[i] = Integer.parseInt(myString[i]); 
    } 
    return cpuUsageAsInt; 
} 

private String executeTop() { 
    java.lang.Process p = null; 
    BufferedReader in = null; 
    String returnString = null; 
    try { 
     p = Runtime.getRuntime().exec("top -n 1"); 
     in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     while (returnString == null || returnString.contentEquals("")) { 
      returnString = in.readLine(); 
     } 
    } catch (IOException e) { 
     Log.e("executeTop", "error in getting first line of top"); 
     e.printStackTrace(); 
    } finally { 
     try { 
      in.close(); 
      p.destroy(); 
     } catch (IOException e) { 
      Log.e("executeTop", 
        "error in closing and destroying top process"); 
      e.printStackTrace(); 
     } 
    } 
    return returnString; 
} 

Amusez-vous avec elle :)