我正在开发一个应用程序,如果按下电源键四次,它将开始发送消息。我已经使用了广播服务和接收器来完成这项工作。
现在的问题是,如果我在早上两次点击电源键,在晚上再点击两次,它仍会发出信息。
我想限制按下电源键之间的时间间隔。
这就是我的接收器的样子。
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();
}
}
}
答案 0 :(得分:0)
创建 CountDownTimer ,在特定时间间隔后将计数器重置为0。请参阅CountDownTimer
答案 1 :(得分:0)
每次收到时都存储时间戳
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()