java – 在android中设置重复警报
作者:互联网
我试图在android中设置一个重复警报,最终将在用户指定的时间上升.然而,一旦设置,警报立即就会响起,即使我确定警报未设置为警报设置之后才会关闭.例如,我将下面的代码设置为在10:43关闭闹钟,所以我将闹钟设置为10:41,但闹钟立即响起.有任何想法吗?提前致谢.
public class Alarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For
Intent scheduledIntent = new Intent(context,ReminderMessage.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
// example
wl.release();
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Date dat = new Date();
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY, 10);
cal_alarm.set(Calendar.MINUTE, 43);
cal_alarm.set(Calendar.SECOND, 0);
if(cal_alarm.before(cal_now)){
cal_alarm.add(Calendar.DATE, 1);
}
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
解决方法:
我想你的路线:
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute
正在触发警报,第二个参数是预定时间,第三个是周期.因此,如果您希望在cal_alarm时间关闭闹钟,则需要使用以下内容:
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), 1000*60*5 , pi); // Millisec * Second * Minute
这应该在cal_alarm时间开始,每5分钟重复一次.
AlarmManager.SetRepeating API Doc
标签:android,java,android-alarms 来源: https://codeday.me/bug/20190725/1537042.html