Android - Find process id of service

     Ever felt the need to find the id of the process hosting a service via code and thought of extracting the same output of "adb shell ps | grep "? 
 
      It seems to work except for the fact that searching by process name is not reliable. However, services in android world are uniquely identified by their name (string) and if you have access to android platform source code, just pull in this change,

         https://android-review.googlesource.com/#/c/19269/

     And its just a question to invoking a API

         ServiceManager.getServicePid("media.audio_flinger");

Update: Few folks have reached out for an existing solution as the Patch was never merged. The closest alternative i came across is to get the pid based on the command line which was used to launch the service process. This works for services hosted in its own process space like media server, surface flinger etc. Android's Process has a hidden API

     public static final native int[] getPidsForCommands(String[] cmds);

     The input parameter is an array of command lines like (/system/bin/mediaserver, /system/bin/surfaceflinger etc). The native logic is brute force which tries to open /proc/pid/cmdline for all known processes in a loop and returns the pid based on the specified command line options. Note that this isn't a process name based check which isn't reliable and is not recommended by framework developers. The downside is that developers need to know the process which hosts the queried service.

No comments: