Service获取全屏点击事件

一个外国老兄的文章帮我解决了

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


Monitor Screen Touch Event in Android

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. Here is 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 touch events outside it. Well, literally, it’s not “invisible”, in fact it’s in foreground all the time! But since it’s so tiny so hopefully users won’t feel a difference.

First, let’s create this dummy view:

1

2

3

4

5

6

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 be parent height. And we also set up a touch event listen of this dummy view, which we’ll implement later.

Then let’s add this dummy view.

1

2

3

4

5

6

7

8

9

10

11

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 view to capture all events on screen, whether or not the event is inside the dummy view or not.

Finally, let’s handle the touch event by implementing View.OnTouchListener listener.

1

2

3

4

5

6

7

8

@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 the underlying real UI elements can get those events.

A final note is that, to keep our dummy view always listening touch events, we need to wrap all these in an Service: we create the dummy view in onCreate and add it to screen in onStartCommand. And the service should implement View.OnTouchListener to receive the touch events.

 

转载于:https://my.oschina.net/u/782560/blog/365574

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值