You can utilize the combination of ActivityLifecycleCallbacks and WindowCallback.
- The
ActivityLifecycleCallbacks
enables you to observe every Activity lifecycle event that occurs in your app. All in one place.
- The
WindowCallback
enables you to intercept many window events. One of the events that gets fired by the system that we are particularly interested in is dispatchTouchEvent.
Now, here is the strategy:
- Register our
GlobalActivityLifecycleListener
in the Application
class
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(GlobalActivityLifecycleListener())
}
}
- Check if the currently displayed Activity is an Ad Activity. If yes, register our
AdWindowCallbacks
class GlobalActivityLifecycleListener : Application.ActivityLifecycleCallbacks {
//...
override fun onActivityResumed(activity: Activity) {
if (isAdActivity(activity)) {
registerWindowCallbacks(activity)
}
}
private fun registerWindowCallbacks(activity: Activity) {
val currentWindow = activity.window
/*This is needed to forward the events from our callback back to the original
callback after we are done with the processing*/
val originalCallbacks = currentWindow.callback
currentWindow.callback = AdWindowCallbacks(originalCallbacks)
}
}
- Intercept/process user touch events
class AdWindowCallbacks(private val originalCallback: Window.Callback) : Window.Callback {
//...
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
//TODO process user touch event
return originalCallback.dispatchTouchEvent(event)
}
}
From there, you can detect the common gestures and act accordingly.