1

我想检测电源按钮是否在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; 
       } 
      } 
     } 
    } 
    } 

代码的执行没有错误,它并不显示敬酒

+0

将你的代码移动到intentservice,因为每次按下电源按钮时都会调用brodcast,所以你的initialTime ,finishTime;复位。使用sharedpreference而不是 –

回答

1
  1. 希望你是动态注册接收器。
    ACTION_SCREEN_OFF -

    您无法通过舱单申报组件收到此,...

  2. 除以下情形:

    if (finishTime - initialTime <= 4000){ Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show(); count = 0; }

没有别的重 - 将计数分配给0,所以如果你错过了一次吐司......计数器不会重置在单次运行0并为<=4000条件以下事件不会进入if,或许您应该重新计数为0,如果是大于3(?)

  • 如果您的烤面包在屏幕关闭时出现点击时出现,则会发生什么情况 - 不会认为它会显示
  • 应该考虑使用||替换if-else,如果您只想检测电源按钮事件,则效果会更好屏幕关闭或开启;像:

    如果(intent.getAction()等于(Intent.ACTION_SCREEN_OFF) || intent.getAction()等于(Intent.ACTION_SCREEN_ON)。){...

  • 如果1。是不是一个问题,目前你的代码看起来不错,它是2和3的组合。4.只是一个建议

    +1

    我已经动态注册了接收器,我很感谢您的建议,并会更新代码。谢谢。 –