如果 30 秒未按下电源键,则重置计数器
Reset the counter if the power key is not pressed for 30 seconds
我正在开发一个应用程序,如果按四次电源键,它就会开始发送消息。我已经使用广播服务和接收器来完成这项工作。
现在的问题是早上按电源键两次,晚上按电源键两次,还是有提示。
我想限制电源键按下的时间间隔。
这是我的接收器的样子。
private static int countPowerOff=0;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
countPowerOff++;
if(countPowerOff==3) {
countPowerOff = 0;
SendMessage sms = new SendMessage(context);
try {
sms.sendSMS();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
catch (IOException ie)
{
ie.printStackTrace();
}
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
countPowerOff++;
if (countPowerOff == 3) {
countPowerOff = 0;
SendMessage sms = new SendMessage(context);
try {
sms.sendSMS();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
创建一个 CountDownTimer 以在特定时间间隔后将计数器重置为 0。参考 CountDownTimer
每次接收时只需存储时间戳
private final static int INTERVAL = 30000; //interval you want int ms
private final static List<Long> times = new ArrayList<Long>();
public boolean shouldSendMessage(){
long current = System.currentTimeMillis();
Iterator<Long> it = times.iterator();
while(it.hasNext()){
Long time = it.next();
if(time<current-INTERVAL){
it.remove(); // remove old times.
}else{
break;
}
}
times.add(current); // add current time
return times.size()==4;
}
并将您的 countPowerOff==3
替换为 shouldSendMessage()
我正在开发一个应用程序,如果按四次电源键,它就会开始发送消息。我已经使用广播服务和接收器来完成这项工作。
现在的问题是早上按电源键两次,晚上按电源键两次,还是有提示。
我想限制电源键按下的时间间隔。
这是我的接收器的样子。
private static int countPowerOff=0;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
countPowerOff++;
if(countPowerOff==3) {
countPowerOff = 0;
SendMessage sms = new SendMessage(context);
try {
sms.sendSMS();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
catch (IOException ie)
{
ie.printStackTrace();
}
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
countPowerOff++;
if (countPowerOff == 3) {
countPowerOff = 0;
SendMessage sms = new SendMessage(context);
try {
sms.sendSMS();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
创建一个 CountDownTimer 以在特定时间间隔后将计数器重置为 0。参考 CountDownTimer
每次接收时只需存储时间戳
private final static int INTERVAL = 30000; //interval you want int ms
private final static List<Long> times = new ArrayList<Long>();
public boolean shouldSendMessage(){
long current = System.currentTimeMillis();
Iterator<Long> it = times.iterator();
while(it.hasNext()){
Long time = it.next();
if(time<current-INTERVAL){
it.remove(); // remove old times.
}else{
break;
}
}
times.add(current); // add current time
return times.size()==4;
}
并将您的 countPowerOff==3
替换为 shouldSendMessage()