Close Activity if Idle

0

I have an application and need to Activity close automatically if idle, ie if the user does not touch the screen for 30 seconds, Activity automatically closes. While the user is using (touching) Activity , it will remain open.

I'm using the CountDownTimer method, but even though the user is using the app, it closes.

Please, could anyone help me?

    
asked by anonymous 03.08.2018 / 16:01

1 answer

2

I usually create applications for interactive totem systems, which always require a timeout . I'll try to explain how I do this:

First I create a class that extends from Application , here I'll call it MyApplication .

Within MyApplication , we'll put these two attributes:

private static int seconds = 30; private static int timeOut = 30;

Where timeOut is the maximum time your screen can be idle, and seconds is the time your counter will decrease.

Once this is done, we will create within MyApplication a TimerTask . Something like this:

private static class Task extends TimerTask {
    @Override
    public void run() {
        seconds--;
        if (seconds < 0) {
            stop();
           //Seu tempo acabou
        }
    }
}

Notice how we decremented our seconds ali.

Now we just need to create the functions for the use of our Task .

private static Timer timer; private static Task timerTask;

  public void start() {
    stop();

    timerTask = new Task();
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 1000, 1000);
}



public static void stop() {
    if (timer != null) {
        timer.cancel();
    }

    if (timerTask != null) {
        timerTask.cancel();
    }

    refresh();
}

public static void refresh() {
    seconds = timeOut;
}

Voilà, you now have the Start function to start your counter, the Stop function to stop, and the refresh function to assign the initial value to the counter.

For use, just call your Activity for: MyApplication.getInstance().start()

Remember to refresh whenever there is an event in your application, you can use this code for this:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    MyApplication.refresh();
    return super.dispatchTouchEvent(ev);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    MyApplication.refresh();
    return super.onKeyUp(keyCode, event);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    MyApplication.refresh();
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    MyApplication.refresh();
    return super.dispatchKeyEvent(event);
}

Just be sure to declare your MyApplication within the <Application> tag in your manifest.

android:name=".MyApplication"

I hope I have helped.

    
03.08.2018 / 19:26