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

最后都变了- 提交于 2019-12-17 03:40:46

问题


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:


回答1:


Hello you can use this code, it works for me in Android 2.3.3:

private String getAppName(int pID)
{
    String processName = "";
    ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRunningAppProcesses();
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while(i.hasNext()) 
    {
          ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
          try 
          { 
              if(info.pid == pID)
              {
                  CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                  //Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +"  Label: "+c.toString());
                  //processName = c.toString();
                  processName = info.processName;
              }
          }
          catch(Exception e) 
          {
                //Log.d("Process", "Error>> :"+ e.toString());
          }
   }
    return processName;
}



回答2:


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 "";
}



回答3:


Kill other processes is generally bad idea..

Look at this Question Android process killer and android task kill..

And also this blog Android: Killing a running process with processid(pid) and package name

And for your question How to get Process Name from pid then

Something like,

Install a terminal emulator, launch it and run:

ps | grep 10058

ps lists the processes and grep filters for the ID you want.

But this only works if the application is running when you run the command.



来源:https://stackoverflow.com/questions/8542326/android-how-to-get-the-processname-or-packagename-by-using-pid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!