App which starts a service which keeps running in background till the user wishes to terminate. How to detect if any other app is opened or closed? I want to start a unique timer for different apps. And finally store all the logs. Any help would be appreciated. Thanks..
Asked
Active
Viewed 126 times
1 Answers
0
Simply get current running task using ActivityManager
ActivityManager mActivityManager= (ActivityManager) mContext
.getSystemService(Activity.ACTIVITY_SERVICE);
if(Build.VERSION.SDK_INT > 20)
{
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else
{
String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
And you can also detect an app processs change's using this Also See this Example

Community
- 1
- 1

Zar E Ahmer
- 33,936
- 20
- 234
- 300
-
I'm getting a error " cannot resolve symbol mContext" – Prajwal Oct 02 '16 at 08:52
-
But it returns all the apps that are currently running. How do I get the app which is "open" or currently being used by the user. – Prajwal Oct 02 '16 at 08:53
-
get(0) is returning current app running – Zar E Ahmer Oct 02 '16 at 09:00
-
`getRunningAppProcesses` returns the unordered list so you cannot get any assumptions about its first element, the docs say: `Returns a list of RunningAppProcessInfo records, or null if there are no running processes (it will not return an empty list). This list ordering is not specified.` – pskink Oct 02 '16 at 09:32
-
getRunningTasks(1).get(0) will do what you need. May be this help http://stackoverflow.com/a/28066580/3496570 – Zar E Ahmer Oct 03 '16 at 05:58