我有三个问题:
1)到目前为止,我已经实现了这一点:
public final class CalculateTime {
public int iHour;
public int iMinute;
public Calendar calendar;
private void calculateRandomNumbers() {
Random randomNumberGenerator = new Random();
iHour = randomNumberGenerator.nextInt(19 - 9) + 9;
iMinute = randomNumberGenerator.nextInt(59);
}
public void calculateRandomTime() {
calculateRandomNumbers();
calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, iHour);
calendar.set(Calendar.MINUTE, iMinute);
}
}
因此,通知应该在9点到19点之间随时推送一次。但是通知在9点到19点之间发送两次。
2)当计算过去时,立即推送通知。
3)我想每周发一次通知,我该如何实施?我试过了:
// For Monday
calendar.set(Calendar.DAY_OF_WEEK, 2)
但我不确定这是否正确,因为我无法轻易测试。 (我不能每次都等一个星期!):/
更多代码,设置闹钟:
public final class NotificationService extends IntentService {
public static final String DESCRIPTION = "description";
public static final String HEADLINE = "headline";
private static final int FM_NOTIFICATION_ID = 0;
public NotificationService() {
super("NotificationService");
}
@Override
protected void onHandleIntent(Intent intent) {
/*
* This method is invoked whenever an intent for this service is fired.
* The actual firing is done by the AlarmManager in the
* TodoEntriesAdapter, but really we don't care at this point where
* exactly the intent came from.
*/
String description = intent.getStringExtra(DESCRIPTION);
String headline = intent.getStringExtra(HEADLINE);
addNotification(description, headline);
}
private void addNotification(String description, String headline) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(headline)
.setContentText(description)
.setAutoCancel(true);
Intent notificationIntent = new Intent(this, ReadNotification.class);
notificationIntent.putExtra("description", description);
notificationIntent.putExtra("headline", headline);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}
}
答案 0 :(得分:0)
通知发送两次。
查看实际与AlarmManager
交互的代码会有所帮助。如果显示所选时间(例如使用日志工具),您将能够看到哪个通知是正确的,以及是否调用了两次调度警报的代码。
当计算过去时,会立即推送通知。
这是documented behaviour。您需要手动检查时间是否过去,如果是,则需要将其向前移动一周。
我想每周发一次通知。
尝试setRepeating(type, start, 7 * AlarmManager.INTERVAL_DAY, operation)
。
我无法轻易测试。
除了手动更改手机日期的原始方法之外,您还可以通过模拟AlarmManager类来测试应用程序(将其替换为使用正确参数检查正确方法的虚拟类)。