Android: How to get the process id of the foreground app Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Android: How to get the process id of the foreground app without wasting too much if your time.

The question is published on by Tutorial Guruji team.

First of all, please note that this question is not same as all the “android foreground app” questions I found on SO, please read on 🙂

I’m trying to write an android app for my own use, using golang, without using android-sdk or ndk (this is the KEY point). It is pretty simple, just use golang to write a http service, compile it for arm CPU and voila my app is running and can be access by simply visit http://localhost.

For the purpose of my app, I need to know the currently running foreground application, to define it precisely:

  1. Foreground application is the application that occupies the screen, or has an “activity” what-so-ever (forgive me I’m not an android developer).

  2. Anything that that is depended by the foreground application (e.g. services) is NOT what I am interested in.

  3. If the phone is LOCKED/screen turned off, I want the solution to tell me there is NO foreground app.

And since I do not use anything android, just treat the phone as a LINUX machine, I want the solution to use native LINUX ways, e.g. by inspect /proc, or by calling any installed android command line tool (including sending messages via these command line tools), but NOT using any SDK/NDK way so that I have to use java or incorporate these thing into my app.


Starting from Android SDK 26 (if I remember well) Apps are executed on -one-User-per-App, so (i.e.) WhatsApp is running on UID=30 and Telegram on UID=76, so executing a ROOT command of “ps -A -o PID,USER,NAME” you can parse output and then Kill all Processes that you don’t want to be executed.

36119 u30_a149     <WhatsApp_packagename>
36203 u76_a211     <Telegram_packagename>
37399 root         [kworker/1:2H]
37423 u0_a329      su
38069 root         sh

Without Root Permissions nothing of what you’re trying to achieve is possible simply because is not possibile to denied an application to be executed or to kill it without Superuser privilege.

We are here to answer your question about Android: How to get the process id of the foreground app - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji