Search code examples
androidontouchlistenertouch-eventmotionevent

Event called when the user is touching the screen?


Welcome all

I'm developoing a game. I want that when the user touches the screen, a laser must be fired constantly each 100ms from bottom part of the screen to the x,y coordinates touched, until the user stop touching the screen. I have the laser working but now i need to fire it constantly each 100ms.

I am ovewriting onTouch event and the problem is that i dont know how to achieve my needs. I want to launch a laser each 100ms if the user is touching the screen.

If i put the laser animation in the onTouch MotionEvent.ACTION_MOVE event, then the laser is only being throwed if the finger is moved. But i want that the laser is thrown each 100ms without moving the finger.

Also MotionEvent.ACTION_DOWN don't work because it is called only one time, when the user touches the screen but only one time

How can my needs be achieved?


Solution

  • There isn't a simple way to get your event every 100ms

    but you can do that:

            class TouchStarted {
            AtomicBoolean actionDownFlag = new AtomicBoolean(true);
    
            Thread loggingThread = new Thread(new Runnable(){
    
                public void run(){
                    while(actionDownFlag.get()){
                        Log.d("event", "Touching Down");
                        try {
                           Thread.sleep(100, 0);
                        } catch (InterruptedException e) {
                        }
                        //maybe sleep some times to not polute your logcat
                    }
                    Log.d("event", "Not Touching");
                }
            });
    
            public void stop() {
                actionDownFlag.set(false);
            }
    
            public void start() {
                actionDownFlag.set(true);
                loggingThread.start();
            }
    
        }
    
        TouchStarted last = null;
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
    
            if(event.getAction()==MotionEvent.ACTION_DOWN){
                if(last != null) last.stop();
                last = new TouchStarted();
                last.start();
            }
            if(event.getAction()==MotionEvent.ACTION_UP){
                last.stop();
            }
        }