Friday, September 1, 2023

Android App Status Check: Code to Identify Running State


During the development of FCM (Firebase Cloud Messaging), I needed logic to determine whether the app was running or not. The problem was that distinguishing the app's execution state proved to be quite tricky from my perspective.
So, I created the following code to make state checks relatively easy. I thought there might be others who face similar considerations, so I'm sharing it.
android activity stack check

In the class that inherits from Application, you can write as shown above in the onCreate method.

If activityStackCnt > 0, it's foreground,
If activityStackCnt == 0, it's background,
This is how you can distinguish it.

In fact, I designed it with the thought that if the app is properly closed by pressing the back button, the count would become negative, resulting in activityStackCnt == 0. However, because the statically declared activityStackCnt is initialized with the default value of 0 for an int, it worked (by chance?) even when the memory was cleared by killing the task from any screen.

0 개의 댓글:

Post a Comment