我在这个网站上搜索了一些与设置闹钟相关的答案,我已经成功地设置了闹钟。
我的做法是:
这是前一节(c)中提到的代码参考:
我的做法是:
- 从一个活动中设置一个闹钟,在特定的时间和日期调用接收器
- 从接收器中调用服务
- 从服务中发送通知(在通知栏上)给用户。
我设置了一个闹钟,在5分钟后。假设我关闭手机并重新打开它(似乎它会忘记闹钟)。如何防止这种情况发生?
我真的需要调用服务来发送通知吗,还是可以从接收器中完成?
Intent intent = new Intent(MyActivity.this,
AlarmReceiver.class);
intent.putExtra("alarm_message", "Something");
PendingIntent mAlarmSender;
mAlarmSender = PendingIntent.getBroadcast(
MyActivity.this, 0, intent, 0);
// We want the alarm to go off 30 seconds from now.
long alarmTime = dateMgmt.getTimeForAlarm(pickedDate);
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmTime + 15000,
mAlarmSender);
这是前一章节(b)提到的代码:
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
Intent newIntent = new Intent(context, MyService.class);
context.startService(newIntent);
} catch (Exception e) {
Toast
.makeText(
context,
"There was an error somewhere, but we still received an alarm",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
这是前一节(c)中提到的代码参考:
@Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}