How to get pid of android application without using adb shell?

AndroidPid

Android Problem Overview


How can I get an android application pid without using adb shell? Is there any API to get pid. any help will be appreciated

Android Solutions


Solution 1 - Android

As every application has its own process id, one can get it by

int pid = android.os.Process.myPid();

Solution 2 - Android

This also works:

ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
int processid = 0;
for (int i = 0; i < pids.size(); i++) {
    ActivityManager.RunningAppProcessInfo info = pids.get(i);
    if (info.processName.equalsIgnoreCase("here your package name")) {
       processid = info.pid;
    } 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRanjitRockView Question on Stackoverflow
Solution 1 - AndroidMohammed Azharuddin ShaikhView Answer on Stackoverflow
Solution 2 - Androidkiran boghraView Answer on Stackoverflow