音量按钮长按事件

时间:2017-04-28 13:18:00

标签: android

我想在特定时间按下音量调高按钮时发出一个干杯消息。

public class MainActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
    if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode,event);
}
@Override
public boolean onKeyLongPress(int keyCode,KeyEvent event){
    if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){
        Toast.makeText(this, "Volume Up Pressed", Toast.LENGTH_SHORT).show();
        return true;
    }
    return onKeyLongPress(keyCode,event);
} }

这里长按正在制作祝酒词但是我想在按下按钮5秒时给它干杯,我该如何给出特定的持续时间呢!

1 个答案:

答案 0 :(得分:1)

声明全局计数变量:int count = 0int key, keyEvent;

在按键按下方法

中添加此项
public class MainActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
 if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){
     key = keyCode;
     keyEvent = KeyEvent.KEYCODE_VOLUME_UP;
    new CountDownTimer(5000, 1000) {

public void onTick(long millisUntilFinished) {
    if(key==keyEvent){
      count++; 
    }
     else{
      count = 0;
     }  
}
public void onFinish() {
    if(count = 5){
      //Notify Them it's been 5 seconds
      }
     count = 0;
 }
}.start();
    return true;
  }
 return super.onKeyDown(keyCode,event);
}