http://jhshi.me/2014/11/09/monitor-screen-touch-event-in-android/index.html
In one of my projects I need to track every screen touch event in background.That is, my app needs to be "invisible" while capturing every screen touch. Hereis how I achieved this.
The idea is to define a dummy UI fragment that is really tiny (say, 1x1 pixel),and place it on one of the corners of the screen, and let it listen on all touchevents outside it. Well, literally, it's not "invisible", in fact it's inforeground all the time! But since it's so tiny so hopefully users won't feel adifference.
First, let's create this 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 we set the width of the dummy view to be 1 pixel, and the height to beparent height. And we also set up a touch event listen of this dummy view, whichwe'll implement later.
Then let's add this 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 is the FLAG_WATCH_OUTSIDE_TOUCH flag, it enables the dummy viewto capture all events on screen, whether or not the event is inside the dummyview or not.
Finally, let's handle the touch event by implementing View.OnTouchListenerlistener.
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "Touch event: " + event.toString());
// log it
return false;
}
We need to return false since we're not really handling the event, so that theunderlying real UI elements can get those events.
A final note is that, to keep our dummy view always listening touch events, weneed to wrap all these in an
Service: we create the dummy view in onCreateand add it to screen in
onStartCommand. And the service should implementView.OnTouchListener to receive the touch events.
本文介绍了一种方法,在Android应用的后台场景下捕捉屏幕触摸事件,通过定义一个极小的虚拟UI碎片来实现,该碎片放置在屏幕的一角并监听所有外部触摸事件。文章详细解释了如何创建、配置和实现这一解决方案,以及如何将其整合到Service中以保持持续监听。

被折叠的 条评论
为什么被折叠?



