android - Listen for touch events in background -


is there legal way in android listen touch events user makes, outside app. mean have service listens screen gestures in background.

the idea define dummy ui fragment tiny (say, 1x1 pixel), , place on 1 of corners of screen, , let listen on touch events outside it. well, literally, it's not "invisible", in fact it's in foreground time! since it's tiny users won't feel difference.

first, let's create dummy view:

mwindowmanager = (windowmanager) mcontext.getsystemservice(context.window_service); mdummyview = new linearlayout(mcontext);  layoutparams params = new layoutparams(1, layoutparams.match_parent); mdummyview.setlayoutparams(params); mdummyview.setontouchlistener(this); 

here set width of dummy view 1 pixel, , height parent height. , set touch event listen of dummy view, we'll implement later.

then let's add dummy view.

layoutparams params = new layoutparams(     1, /* width */     1, /* height */     layoutparams.type_phone,     layoutparams.flag_not_focusable |      layoutparams.flag_not_touch_modal |     layoutparams.flag_watch_outside_touch,     pixelformat.transparent     ); params.gravity = gravity.left | gravity.top; mwindowmanager.addview(mdummyview, params); 

the key here flag_watch_outside_touch flag, enables dummy view capture events on screen, whether or not event inside dummy view or not.

finally, let's handle touch event implementing view.ontouchlistener listener.

@override public boolean ontouch(view v, motionevent event) { log.d(tag, "touch event: " + event.tostring());  // log  return false; } 

we need return false since we're not handling event, underlying real ui elements can events.

a final note that, keep our dummy view listening touch events, need wrap these in service: create dummy view in oncreate , add screen in onstartcommand. , service should implement view.ontouchlistener receive touch events.

referrence got here http://jhshi.me/2014/11/09/monitor-screen-touch-event-in-android/


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -