如何在5秒内检查用户是否触摸屏幕

时间:2017-04-28 07:55:15

标签: android timer ontouchlistener

我想在活动中计算5秒并检查用户是否正在触摸屏幕的任何部分,如果用户未在5秒内触摸,则我想显示此信息。我怎么能这样做?

INSERT AS SELECT

1 个答案:

答案 0 :(得分:4)

首先在onCreate()部分

中调用此方法
    LinearLayout mLinearLayoutMain = (LinearLayout) findViewById(R.id.your_id); // Set your Layout
    mLinearLayoutMain.setOnTouchListener(this);
    startTimer();

确保您的活动实施

implements View.OnTouchListener{

<强> startTimer所()

public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 10000ms the TimerTask will run every 10 seconds
        timer.schedule(timerTask, 10000, 10000); //
    }

,然后

public void cancelTask() {
    //stop the timer, if it's not already null
    if (timer != null) {
        timer.cancel();
        timer = null;
        Log.d("cancel","Amiyo");

        startTimer();;
        Log.d(" startTimer","Amiyo");
    }
}

public void initializeTimerTask() {

    timerTask = new TimerTask() {
        public void run() {

            //use a handler to run a toast that shows the current timestamp
            handler.post(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(),"No action taken within 5 seconds ",Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
}

public boolean onTouch(View v, MotionEvent event)
{
    Log.d("Hi","Touching");
    cancelTask();

    return false;//false indicates the event is not consumed
}

全球声明

Timer timer;
TimerTask timerTask;

//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();