我想在活动中计算5秒并检查用户是否正在触摸屏幕的任何部分,如果用户未在5秒内触摸,则我想显示此信息。我怎么能这样做?
INSERT AS SELECT
答案 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();