Android How to - Get package name of the process id








Question

We would like to know how to get package name of the process id.

Answer

import java.util.List;
//  w w  w. j  a v  a2s.  c  om
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

class ActivityUtils {
  /**
   * Get package name of the process id.
   * @param context
   * @param pid
   * @return
   */
  public static final String getPackageNameFromPid(Context context, int pid) {
      ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      List<RunningAppProcessInfo> processes = am.getRunningAppProcesses();
      for (RunningAppProcessInfo info : processes) {
          if (info.pid == pid) {
              String[] packages = info.pkgList;
              if (packages.length > 0) {
                  return packages[0];
              }
              break;
          }
      }
      return null;
  }
}