我想点击相应的按钮,将 AlarmManager 的时间更改为1天,3天和7天。例如,如果我点击" 1天"按钮,警报应设置为每天重复的方式,等等。但我不知道如何实现这一点,我有代码在预先定义的时间内重复闹钟
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, NotifyService.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
long recurring = (1 * 60000 * 60 * 24); // repeat every 24 hrs
am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis(), recurring, sender);
}
public void set1day(View view) {
//...
}
public void set3days(View view) {
//...
}
public void set7days(View view) {
//...
}
}
答案 0 :(得分:1)
间隔日可以使用默认常量。您应该使用它们而不是计算间隔的秒数。喜欢这个:
单日间隔
public void set1day(View view) {
am.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
}
持续3天
public void set3day(View view) {
am.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis(), AlarmManager.INTERVAL_DAY*3, sender);
}
任何n天的间隔
am.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis(), AlarmManager.INTERVAL_DAY*n, sender);
此外,从API 19开始,所有重复警报都不准确。使用setInexactRepeating
以避免电池耗尽。