我想要什么:用户保持点击按钮 1900 毫秒。如果他在 1900 毫秒之前拿起手指,手机就会停止振动。如果他将手指放在按钮上超过 1900 秒,calculate()方法就会运行。 我正在使用:postDelayed,因为我阅读它不会干扰 ui 线程。我试图检查是否已经过了 1900 秒,用户还没有拿起他的手指,即使是计算方法运行。 发生错误:如果用户在 1900 秒之前拨动手指,或者只是触摸并立即拨动,手机会一直振动。虽然它不应该发生,因为我正在使用 MotionEvent.ACTION_UP 检查它。请帮忙 !!
int flag = 0;
int aborted_flag = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
Handler mHandler = new Handler();
if(event.getAction()==MotionEvent.ACTION_DOWN){
scanning();
t1 = System.currentTimeMillis();
vibrator.vibrate(1900);
mHandler.postDelayed(new Runnable() {
public void run() {
check();
}
}, 1901);
}
if(event.getAction()==MotionEvent.ACTION_UP){
if(flag == 0){
t2 = System.currentTimeMillis();
vibrator.cancel();
calculate();
aborted_flag = 1;
}
}
return true;
}
private void check() {
t2 = System.currentTimeMillis();
Log.e("Hello","Inside Check");
Log.e("Hello",""+aborted_flag);
vibrator.cancel();
if(aborted_flag==0){
calculate();
flag = 1;
}
}
private void scanning() {
textView.setText("Scanning");
}
private void calculate() {
Log.e("t2-t1 ", t2-t1+"");
if(t2-t1>=1900){
Random r = new Random();
int k = r.nextInt((5 - 0) + 1) + 0;
textView.setText(str[k]);
////////////animation library code/////////////
YoYo.with(Techniques.StandUp)
.duration(700)
.playOn(findViewById(R.id.text_view));
////////////////////////////////////////
changeBackgroundColor(k);
//textView.setTextColor(Color.parseColor("#00ff00"));
flag = 0;
}
else{
textView.setText("Aborted\n Try Again");
relativeLayout.setBackgroundResource(R.color.red);
}
}
public void changeBackgroundColor(final int k) {
runOnUiThread(new Runnable(){
public void run() {
switch(k){
case 0: relativeLayout.setBackgroundResource(R.color.blue);
break;
case 1: relativeLayout.setBackgroundResource(R.color.pink);
break;
case 2:;
case 3: relativeLayout.setBackgroundResource(R.color.green);
break;
default:relativeLayout.setBackgroundResource(R.color.yellow);
}
}
});
}