I have an app which track user activity on app which include time etc, Now if user has opened the app, It will start an session and till user in this app , his session will continue, He can switch to multiple activity. Now meantime he switches to another app, His session logging should be stopped and written down to file

What I tried

I created one base activity and 
On resume event if counter is zero, I start session and increment counter and 
On stop event , i decrement counter and if counter is zero, I stop session

But this will not calculate actual problem of tracking as android doesn't stop activity as user switch to another app.

So is there any way to achieve such thing.

Additional:

If we can get whether app activity is active on screen so event can be used to start or end session.