如何使服务侦听onTouchEvent

时间:2014-03-02 14:07:01

标签: android android-service android-view

我正在尝试使用以下代码来侦听来自服务的触摸事件

  public void onCreate() {
        super.onCreate();
    //    Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
        mView = new HUDView(this);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        //return super.onTouchEvent(event);

         final int action = ev.getAction();
         //   switch (action & MotionEvent.ACTION_MASK) {
         //   case MotionEvent.ACTION_DOWN: {
                final float x = ev.getX();
                final float y = ev.getY();
                Points p = new Points();
                p.setPoints(x,y);
                list.add(p);


        return true;
    }

此代码在Android ver 2.3上运行完美,但在版本4.0和4.1中未调用onTouchEvent。可能是什么问题

我正在尝试从服务中侦听点击,服务附加了一个Activity。该活动照常使用,但服务保持记录点击。当使用TYPE_SYSTEM_OVERLAY时,它在Android 2.3上工作得很好,但在4.1上没有调用onTouchEvent。使用TYPE_SYSTEM_ALERT时,会调用onTouchEvent,但触摸事件不会传递给活动,并且无法响应。

1 个答案:

答案 0 :(得分:0)

试试这个:

findViewById(R.id.someView).setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent ev) {
        final int action = ev.getAction();
        final float x = ev.getX();
        final float y = ev.getY();
        Points p = new Points();
        p.setPoints(x,y);
        list.add(p);

        return true;        
    }
});