空闲时关闭活动

时间:2018-08-03 16:42:14

标签: android android-activity timeout

我有一个应用程序,我需要Activity在空闲时自动关闭,也就是说,如果用户在30秒内没有触摸屏幕,Activity会自动关闭。当用户使用(触摸)Activity时,它将保持打开状态。

我正在使用CountDownTimer方法,但是即使用户正在使用该应用程序,它也会关闭。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以像这样使用touch listener并重置倒数计时器或用于关闭活动的线程

@Override
public boolean onTouchEvent(MotionEvent event) {
    //mGestureDetector.onTouchEvent(event);

int action = event.getActionMasked();

switch (action) {

    case MotionEvent.ACTION_DOWN:
        initialX = event.getX();
        initialY = event.getY();

        Log.d(TAG, "Action was DOWN");
        break;

    case MotionEvent.ACTION_MOVE:
        Log.d(TAG, "Action was MOVE");
        break;

    case MotionEvent.ACTION_UP:
        float finalX = event.getX();
        float finalY = event.getY();

        Log.d(TAG, "Action was UP");

        if (initialX < finalX) {
            Log.d(TAG, "Left to Right swipe performed");
        }

        if (initialX > finalX) {
            Log.d(TAG, "Right to Left swipe performed");
        }

        if (initialY < finalY) {
            Log.d(TAG, "Up to Down swipe performed");
        }

        if (initialY > finalY) {
            Log.d(TAG, "Down to Up swipe performed");
        }

        break;

    case MotionEvent.ACTION_CANCEL:
        Log.d(TAG,"Action was CANCEL");
        break;

    case MotionEvent.ACTION_OUTSIDE:
        Log.d(TAG, "Movement occurred outside bounds of current screen element");
        break;
}

return super.onTouchEvent(event);

}

答案 1 :(得分:0)

如何取消和启动计时器。

@Override
public void onUserInteraction() {
    super.onUserInteraction();
    yourCountDownTimer.cancel();
    yourCountDownTimer.start();
}