gpt4 book ai didi

使用电源按钮打开和关闭 Android 屏幕

转载 作者:行者123 更新时间:2023-11-30 00:35:12 29 4
gpt4 key购买 nike

我正在尝试检测电源按钮是否在 4 秒内被按下 3 次。以下代码无效。

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;
}
}
}
}
}

代码执行无误,不显示toast

最佳答案

  1. 希望您正在动态注册接收器。
    ACTION_SCREEN_OFF --

    You cannot receive this through components declared in manifests,...

  2. 以下情况除外:

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

没有其他方法将计数重新分配为 0,因此,如果您错过了一次 toast ......计数器不会在单次运行中重置为 0,<=4000 的以下事件条件不会输入 if ,如果计数大于 3 (?),也许您应该将计数重新分配给 0

  1. 如果您的 toast 在屏幕关闭时出现在点击过程中会怎样——不要认为它会可见
  2. 应考虑使用 ||如果您只想检测电源按钮事件而不考虑屏幕关闭或打开,则替换 if-else 会更好;喜欢:

    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)|| intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { ...

如果 1. 没有问题,目前您的代码似乎没问题,它是 2. 和 3. 的组合。4.只是一个建议

关于使用电源按钮打开和关闭 Android 屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43539432/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com