我正在开发一个售货亭,现在在管理方面.为了进入管理员,用户需要在3秒钟内点击屏幕5次,否则什么都不会发生.任何人都可以帮我解决这个问题吗?先感谢您!
Car*_*les 44
请阅读代码中的注释,这非常简单
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
public class MainActivity extends Activity {
private int count = 0;
private long startMillis=0;
//detect any touch event in the screen (instead of an specific view)
@Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
if (eventaction == MotionEvent.ACTION_UP) {
//get system current milliseconds
long time= System.currentTimeMillis();
//if it is the first time, or if it has been more than 3 seconds since the first tap ( so it is like a new try), we reset everything
if (startMillis==0 || (time-startMillis> 3000) ) {
startMillis=time;
count=1;
}
//it is not the first, and it has been less than 3 seconds since the first
else{ // time-startMillis< 3000
count++;
}
if (count==5) {
//do whatever you need
}
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我的解决方案类似于Andres的解决方案.当您第一次抬起手指时,也就是当我认为水龙头完成时,倒计时开始.这类似于点击,当您释放鼠标按钮时发生单击.从第一次升降3秒后,计数器复位.另一方面,Andres的approch使用基于将手指放在屏幕上的逻辑.它还使用了一个额外的线程.
我的逻辑是许多可能的逻辑之一.另一种合理的方法是在抽头流中在3秒内检测到5次连续抽头.考虑:
TAP1,2000毫秒,TAP2,500毫秒,TAP3,550ms,tap4,10毫秒,tap5,10毫秒,tap6.
第二到第六个水龙头在不到3秒的时间内包含一组五个水龙头; 在我的方法中,这将无法被发现.要检测到这一点,您可以使用固定大小为5的FIFO队列并记住最后5个时间戳:此序列正在增加.当您收到新的水龙头时,您可以检查1)是否至少发生了5次水龙头,以及2)最旧的时间戳是否不老,然后是3秒.
无论如何,回到第一个逻辑,将此代码放在Activity:
private int mCounter = 0;
private Handler mHandler = new Handler();
private Runnable mResetCounter = new Runnable() {
@Override
public void run() {
mCounter = 0;
}
};
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mCounter == 0)
mHandler.postDelayed(mResetCounter, 3000);
mCounter++;
if (mCounter == 5){
mHandler.removeCallbacks(mResetCounter);
mCounter = 0;
Toast.makeText(this, "Five taps in three seconds", Toast.LENGTH_SHORT).show();
}
return false;
default :
return super.onTouchEvent(event);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您可能还希望在配置更改上保留一些状态.正如数学家所说,我把它作为练习给读者
| 归档时间: |
|
| 查看次数: |
10968 次 |
| 最近记录: |