androidtouchandroid-serviceandroid-touch-event

Android service listen to touch event


I would like to collect touch input (position and pressure) in an Android 5.1 application. This is possible with an onTouchListener binded to a specific view. But I would like to collect the touch events in a service (running in the background) and not bound to a specific view.

Is it somehow possible to collect touch events in a service?


Solution

  • Basically - yes. You can pass any View into your Service and add touch event listener there. But with this you can face serious memory leak problems, because with Viewyou'll pass Activity of Fragment Context. Maybe it can work with some ServiceConnection and managing onCreate/onDestroy (activity/fragment lifecycle).

    But! Really better approach will be overriding Activity and then inherit from it all your other activities. There you'll have slightly reduced chance of memory leak. You can try to add onTouchEvent listener to activity decor view and receive touch events for whole screen. Or even add some invisible view in front of all views and track touches there (I'm not sure if DecorView variant will work). And then pass touches wherever you want.