我想检测电源按钮是否在4秒内按下三次。下面的代码不起作用。Android屏幕开启和关闭使用电源按钮处理
public class PowerButtonReceiver extends BroadcastReceiver{
static int count = 0;
long initialTime,finishTime;
@Override
public void onReceive(final Context context, Intent intent) {
Log.v("onReceive", "Power button is pressed.");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
if (count == 0){
initialTime = System.currentTimeMillis();
}
count++;
if (count == 3){
finishTime = System.currentTimeMillis();
if (finishTime - initialTime <= 4000){
Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show();
count = 0;
}
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
if (count == 0){
initialTime = System.currentTimeMillis();
}
count++;
if (count == 3){
finishTime = System.currentTimeMillis();
if (finishTime - initialTime <= 4000){
Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show();
count = 0;
}
}
}
}
}
代码的执行没有错误,它并不显示敬酒
将你的代码移动到intentservice,因为每次按下电源按钮时都会调用brodcast,所以你的initialTime ,finishTime;复位。使用sharedpreference而不是 –