Is there a native android way to get a reference to the currently running Activity from a service?
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.
Example here
There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.
Once you have that you can get a ComponentName object by requesting the topActivity from your list.
Here's an example.
You will need the following permission on your manifest:
Just recently found out about this. With apis as:
targetSdkVersion 26
ActivityManager.getCurrentActivity(context)
Hope this is of any use.
Use
ActivityManager
If you only want to know the application containing the current activity, you can do so using
ActivityManager
. The technique you can use depends on the version of Android:ActivityManager.getRunningTasks
(example)ActivityManager.getRunningAppProcesses
(example)Benefits
Disadvantages
ActivityManager.RunningAppProcessInfo.processState
Example (based on KNaito's code)
Manifest
Add the
GET_TASKS
permission toAndroidManifest.xml
:It can be done by:
Implement your own application class, register for ActivityLifecycleCallbacks - this way you can see what is going on with our app. On every on resume the callback assigns the current visible activity on the screen and on pause it removes the assignment. It uses method
registerActivityLifecycleCallbacks()
which was added in API 14.In your service call
getApplication()
and cast it to your app class name (App in this case). Than you can callapp.getActiveActivity()
- that will give you a current visible Activity (or null when no activity is visible). You can get the name of the Activity by callingactiveActivity.getClass().getSimpleName()
Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.
I don't know if it's a stupid answer, but resolved this problem by storing a flag in shared preferences every time I entered onCreate() of any activity, then I used the value from shered preferences to find out what it's the foreground activity.