We recently had to implement a session timeout functionality in an Android app. We decided to expire the session (log the user out form the app) after 30 minutes of inactivity. The first thing to do here is the define what “inactivity” means. Our business analyst decided that not touching the app for 30 minutes meant the user was not interacting with the app. For most of the apps this is an acceptable criteria, but that are other cases were it might not make sense (for example trading apps, where the user can leave the app open for longer periods to monitor his positions).
Since in our case inactivity meant no touch, we needed a way to trap a touch in an Android Activity (before it gets dispatched to a UI control). Luckily for us, that’s really easy to do in Android: the Activity class has the method dispatchTouchEvent(MotionEvent event). We implemented that in our superclass and now we’re notified every time there’s a touch on the UI). Don’t forget to return false in that method to allow the event to travel up the hierarchy of UI controls. Otherwise, no UI controls will respond to the events that you want to catch.
Here’s the full method: