因此,我编写了一个代码,其中警报管理器应在准确的时间触发并每分钟重复一次,并且它部分起作用,第一次触发,但在给定间隔(一分钟)后不再重复。
主要活动:
public void SetAlarm()
{
final Button button = findViewById(R.id.button); // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive( Context context, Intent _ )
{
Toast.makeText(context, "Nope", Toast.LENGTH_SHORT).show();
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.setInexactRepeating( AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000*5, 6000, pintent );
}
public void klik(View view) {
SetAlarm();
}
}
尝试使用setRepeating。 manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
cal.getTimeInMillis() + 1000*5, 6000, pintent );
有关最佳做法,您可以参考此文档-https://developer.android.com/training/scheduling/alarms
用途:
manager.setRepeating( AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000*5, 6000, pintent );
而不是:
manager.setInexactRepeating( AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000*5, 6000, pintent );
为了安全起见,我认为以毫秒为单位的最小重复次数是15000:]