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;
//from w  w w  . java 2 s.co m
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

public class Main {

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