开发者

How to setup an alarm that would go off even if I restart my android phone?

I've been searching this site and found some answers related to setting an alarm. I've successfully been able to set up an alarm.

What I do is:

  • From an activity I set an alarm that at certain time and date will call a receiver
  • From the receiver I call a service
  • From the service I send a notification (on the notification bar) to the user.

My questions are:

  1. I set up an alarm 5 minutes from now. Say I turn off the phone and turn it back on (it seems it forgets the alarm). How can I prevent this from happening?

  2. Do I really need to call a service to send the notifications or can I do it from the receiver?

The following is the code referenced on previous section (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);

This is the code referenced on previous section (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 e开发者_StackOverflow社区rror somewhere, but we still received an alarm",
       Toast.LENGTH_SHORT).show();
   e.printStackTrace();

  }

This the code referenced on previous section (c):

 @Override
 public void onCreate() {
  super.onCreate();
  nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  showNotification();
 }


You don't need to call a service to send the notifications, you can do it from the receiver.

I don't think there is a way to save the alarm after a power off. What I would do:

  • Start a service at boot.
  • Check if an alarm need to be settled.

Notice that you would need to save the alarm info somewhere. Check Android's Data-storage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜