Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

process - Android - How to get the processName or packageName by using PID?

MY QUESTION: What could I use to retrieve the processName or packageName of a certain process given its PID?

Since in my task manager I wanted to use the PID while utilizing the killBackgroundProcesses code to kill the processes. Problem is I need the packageName/processName to do that and it would be such a hassle to the user if I asked them to type in the processName rather than just typing its PID.

here's the image of my task manager:

http://i.imgur.com/1zpXg.jpg

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code is a simplified version of Yaqub's code. I use this as a static method in a Util class:

public static String getAppNameByPID(Context context, int pid){
    ActivityManager manager 
               = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    for(RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()){
        if(processInfo.pid == pid){
            return processInfo.processName;
        }
    }
    return "";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...