How to detect when the user launches another app? (Android)

I'm trying to build an application where my application runs in the background and detects when the user launches another application so that I can control the flow from thereon. To illustrate my query, I'd like to specify an example. My application is running in the background (say as a Service), and the user has just clicked on application 'XYZ'. Is it possible for my app to detect that app 'XYZ' has been launched? More than just detecting whether 'XYZ's Activity has come to the foreground,I want to detect whther 'XYZ' has been launched or not. Say someone launches 'Whatsapp Messenger', I want to know if my app can know that 'Whatsapp Messenger' has been launched.

EDIT : A lot of people think I'm trying to build malware, but I'm not. I'm trying to build an app for a high school project. I want a stat to see how often I use my camera as part of a psych project. :/

Thanks in advance, Sumit.


Yes, You can find the which application is launched, by Tracking the Logcat. Just Track on ActivityManager tag with info -I log.

From adb shell Command is,

adb logcat ActivityManager:I *:S

From your application code,

logcat ActivityManager:I *:S

And in Logcat you can find a line something like,

I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}

When any application will launched.

It is logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

Update:

Just add permission in your Application's manifest file,

android.permission.READ_LOGS

I guess you should have a look at "app protector" applications in the Google Play. They detect that user launched another application. That is done by reading system logs. Try opening LogCat and reading logs after you launched any application on device. You'll be surprised.

And where should you go from there? I guess you should try aLogCat app. It's freen and open-source. That will help you to actually read logs.

All this is considered to be a security breach in Android by some developers, though.