如何通过pid获取应用程序包名称?

时间:2013-01-05 03:11:15

标签: android

String callerPackage = getAppNameByPID(getContext(), Binder.getCallingPid());
private String getAppNameByPID(Context context, int callingPid) {
//How ?
    ....

    }

我的问题: 如何通过pid获取应用程序包名称?

2 个答案:

答案 0 :(得分:2)

每个进程可以包含多个包,因此它看起来像:

private String[] getPackageNames(int pid)
{
    ActivityManager activityManager = (ActivityManager)getContext().getSystemService(Activity.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
    for(RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) 
    {
        try 
        { 
            if(runningAppProcessInfo.pid == pid)
            {
                return runningAppProcessInfo.pkgList;
            }
        }
        catch(Exception e) 
        {
        }
    }
    return null;
}

答案 1 :(得分:-1)

你好,你可以尝试这个代码,它对我来说很好。

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