1

Situation
I want to implement a timeout in my app. If the user did not touch the screen within 2 minutes an inactivity fragment will be shown.

What i got so far
I am tracking the activity lifecycle using a custom Application implementing Application.ActivityLifecycleCallbacks. This way i know which Activity is currently on top and can access its FragmentManager to show my inactivity Fragment on timeout. A background Thread constantly checks if the last detected touch was longer ago than 2 minutes.

Problem
I dont know how to detect every touch that happens on the activity. I tried adding a OnTouchListener to activity.getWindow().getDecorView().setOnTouchListener(), but it is only called if the decorview is touched. If for instance a Button on top of it is touched my listener isn't notified. activity.getContentScene()' returns null for me, so i can't access the rootViewGroup` like that either.

Question
How can i detect any touches that happen on a Activity or the whole Application?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Basti
  • 1,117
  • 12
  • 32
  • have you tried to override Activity's method dispatchTouchEvent(MotionEvent ev) ? –  Jul 11 '18 at 14:58
  • Possible duplicate of [How to set OnTouchListener for the entire screen?](https://stackoverflow.com/questions/17773835/how-to-set-ontouchlistener-for-the-entire-screen) – Timothy Winters Jul 11 '18 at 14:58
  • @TimothyWinters doesn't solve my problem. – Basti Jul 12 '18 at 10:42
  • @Subzero I don't have access to the source of all my activities. I need to implement it generic without editing any Activities source. – Basti Jul 12 '18 at 10:42
  • @Basti Did you find a solution for this? – n_r Aug 22 '22 at 12:45

1 Answers1

0

override dispatch touch event in your activity

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect viewRect = new Rect();
    view.getGlobalVisibleRect(viewRect);

//or 

  int x= ev.getRawX();
     int y= ev.getRawY();


         if(/*check bounds of your view*/){
          // set your views visiblity to gone or what you want. 
         }
      //for prevent consuming the event.


    return super.dispatchTouchEvent(ev);
}
Rohit Sharma
  • 1,384
  • 12
  • 19
  • 1
    I don't have access to all activities in my app. I need to implement it generic without editing any activities source. – Basti Jul 12 '18 at 10:43
  • Make a base activity override this method in it and extend all your activity with the base activity or you can make a helper static method in a different class where you can write your logic and access it from whereever you want – Rohit Sharma Jul 12 '18 at 10:49
  • Again. I CANT change the source of all activities in my project. So i can't adjust the dispatchTouchEvent method of all my activities. – Basti Jul 12 '18 at 13:09
  • If you will find a way please post the answer – Rohit Sharma Jul 13 '18 at 03:57