tags:

views:

70

answers:

1

Hi:

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 error 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();
 }
+2  A: 

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:

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

Macarse
Oh wao!!!Thank you very much for your answer... I'll try an let you know how it goes...As for the alarm's information saved i got it in a table (because there will be an alarm per item). But I guess I'll need the service to go to the alarm info and check if it needs to go off.Cheers :-)
monn3t
Worked beautifully and is exactly what I wanted to do in the first place.Muchas Gracias, funcionó a la perfección.
monn3t