2 sachinks SachinKS 于 2013.01.05 13:20 提问

谁会通过pid获取app包名?谢谢
String callerPackage = getAppNameByPID(getContext(), Binder.getCallingPid());
private String getAppNameByPID(Context context, int callingPid) {
//How ?
    ....

    }

如题,如何通过pid获取app包的名字?

2个回答

cytown
cytown   2013.01.05 14:39
已采纳

通过ActivityManager.getRunningProcesses和getRunningServices来获得,然后比对列表中的pid即可。

注意,1个pid有可能会对应多个package。

Kakalapa1986
Kakalapa1986   2013.01.05 15:17
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;
}

用这个代码应该就可以了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!