Lately I'm working on a library able to detect all touches easy to integrate with current apps, so after some R&D this are my conclusions.

 

First approach: Override the dispatchTouchEvent on all activities... founded while reading StackOverflow this is the easy way (and android prepared way) to handle gesture on full activity works perfectly what force you to change all your actvities and is hard to integrate with existing apps.

 

Second approach: Once the activity is created, found the rootview of the activity and recursively apply on all view tree a setOnTouchListener, except when special views are found (like ListViews). This solution has so many problems that is hard to imagine how this works (actually was what we were using on work on previous versions...)

  1. Since Android doesn't have an API to know if some listener was previusly setted, you problably destroying some touch listener on you way and the app will not work any more as expected.
  2. If the host app programtically adds more views, it's impossible to detect the onTouchListener on this view.
    1. In fact this was solved using a ViewTreeObserver on the root view.



Final approach: Obtain the Window object and use the setCallback method. So now you have intercept for keyEvents and MotionEvents.

Also using the ActivityLifecycleCallbacks, where we can get the window for the current created activity and set the callback.