如何设置一个闹钟,即使我重启了安卓手机也会响起?

4
我在这个网站上搜索了一些与设置闹钟相关的答案,我已经成功地设置了闹钟。
我的做法是:
  • 从一个活动中设置一个闹钟,在特定的时间和日期调用接收器
  • 从接收器中调用服务
  • 从服务中发送通知(在通知栏上)给用户。
我的问题是:
  1. 我设置了一个闹钟,在5分钟后。假设我关闭手机并重新打开它(似乎它会忘记闹钟)。如何防止这种情况发生?

  2. 我真的需要调用服务来发送通知吗,还是可以从接收器中完成?

以下是先前部分(a)引用的代码:
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();
 }

1
参考文档:http://developer.android.com/reference/android/app/AlarmManager.html - jason saldo
1个回答

2
您不需要调用服务来发送通知,您可以从接收器中发送通知。
我认为在断电后没有保存闹钟的方法。我的做法是: 请注意,您需要将闹钟信息保存在某个地方。请参考Android的数据存储

哇哦!!!非常感谢您的回答...我会尝试并让您知道进展情况...至于保存警报信息,我将其存储在一个表格中(因为每个项目都会有一个警报)。但我想我需要服务去检查警报信息并确定是否需要触发。干杯 :-) - monn3t
非常完美地工作了,正是我一开始想要做的。谢谢! - monn3t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接