Reputation: 576
I am currently trying to write an app that will change certain settings automatically (turn off sound, etc) when an application becomes active and to revert back to the original settings when the application is no longer active.
EDITED Sorry, I believe I explained the question poorly. I am currently trying to write an app that will be able to detect when a certain application (for example, youtube app) becomes visible to the user, meaning that the user has just launched/navigated to the youtube app.
When I detect this, I want to perform certain setting changes, such as turning off the phone's sound (I have already figured this part out). And then, when I detect that the youtube app is no longer visible to the user, I want to restore the settings back to what they were.
What I want to know is the mechanism to detect when any application at all (not my application) becomes visible / not visible to the user.
Kind of like what the app Tasker does.
I am trying to figure out how it accomplishes this. There does not seem to be any broadcast receivers that will notify on applications becoming active. One way that I can think of is to create a service that constantly polls the currently running tasks.. but this seems like it will give very bad performance.
Is there any alternative that someone may suggest?
Thank you in advance
Upvotes: 2
Views: 470
Reputation: 6725
You probably want the list of running processes and do something with it.
You can do this using the following code:
ActivityManager actMngr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
//Check pi.processName and do your stuff
//also check pi importance - check if process is in foreground or background
if (pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//DO YOUR STUFF
}
}
Please note that to list processes you need the GET_TASKS permission.
You can do this by adding this to your manifest:
<uses-permission android:name="android.permission.GET_TASKS" />
Upvotes: 2
Reputation: 27004
What do you mean by active? An application is either running or terminated, and you have 2 hooks to change the behaviour of the application onCreate()
and onTerminate()
On the other hand, an application has different components, like activities, and an activity has a more complex lifecycle with similar hooks.
Upvotes: 0