Android 无操作之后定时退出

 android定时器监用户听对页面无操作5分钟退出登录实现 - 简书

private long advertisingTime = 600000;///定时结束退出登录10分(分钟)=600000毫秒
    public CountDownTimer countDownTimer;

    @Override
    protected void onResume() {
        super.onResume();
        //启动定时
        if (isTimedExitApp()) {
            startClock();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    /**
     * @return 页面是否开启无操作定时退出
     */
    public boolean isTimedExitApp() {
        return true;
    }

    /**
     * 计时
     */
    public void startClock() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(advertisingTime, 1000) {//登录状态是时页面5分钟没有操作弹窗提示
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onFinish() {
                    timedExitAppTimeEnd();
                    //定时结束后的操作
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                    }
                }
            };
            countDownTimer.start();
        } else {
            countDownTimer.start();
        }
    }

    /**
     * 定时退出时间到
     */
    public void timedExitAppTimeEnd() {
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!isTimedExitApp()) {
            return super.dispatchTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                startClock();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

你可能感兴趣的:(android,java,开发语言)