3

I have an Activity. All I want is if user don't touch screen, after a TIMEOUT, this activity will automatically finish(). Anyone have any ideas?

tuan.giao
  • 252
  • 1
  • 4
  • 15

4 Answers4

4
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {
            //TODO: Do something every second
        }

        public void onFinish() {

            finish();
            //YourActivity.finish();  outside the actvitiy

        }
    }.start();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            countDownTimer.cancel();
            countDownTimer.start();
        }
        return super.onTouchEvent(event);
    }

So basically you start a countDown timer and than wait for it to get completed. Once completed, call finish on the activity. If in between the user touches the screen, you cancel the timer and start it again.

Don't forget to accept the answer :)

Hardik4560
  • 3,202
  • 1
  • 20
  • 31
0

Look for how to wait/sleep in Android, examples:

wait for 3 seconds or user click

Wait a time - Android

How to "wait" a Thread in Android

And when the wait/sleep ends just call the finish() method.

Community
  • 1
  • 1
Sotti
  • 14,089
  • 2
  • 50
  • 43
0

Try this in your Activity:

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {

         finish();
         //YourActivity.finish();  outside the actvitiy


     }
  }.start();

http://developer.android.com/reference/android/os/CountDownTimer.html

Lavekush Agrawal
  • 6,040
  • 7
  • 52
  • 85
-1

use this :

int time =0;

then add onTouchListener for your root layout and update time value like this :

time = 0;

and use the handler for count like this :

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
    @Override
    public void run() {
    time++;
    if(time>=10000){
            finish();
     }  
    }
    }, 1000);

it is clear i set finish time for 10 second.

Meysam
  • 694
  • 6
  • 20