Tuesday, July 12, 2011

AlarmManager and NotificationManager sample code

This is not a complete tutorial on how to use AlarmManager and NotificationManager, but a simple sample.

The scenario is I want to have an alarm set to certain time. When it goes off, it show notification icon on status bar. When click on the notification, it will start an activity.

1. Create the BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager mNM;
        mNM = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, "Test Alarm",
        System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, TestActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(context, context.getText(R.string.alarm_service_label), "This is a Test Alarm", contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number. We use it later to cancel.
        mNM.notify(R.string.alarm_service_label, notification);
    }
}

2. Add Receiver to Manifest.xml

<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>

3. Set the alarm

public class AlarmService {
    private Context context;
    private PendingIntent mAlarmSender;
    public AlarmService(Context context) {
        this.context = context;
        mAlarmSender = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);
    }

    public void startAlarm(){
        //Set the alarm to 10 seconds from now
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND, 10);
        long firstTime = c.getTimeInMillis();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, firstTime, mAlarmSender);
    }
}

12 comments:

  1. Really very helpful....Simple and Superb....Thanks for your information

    ReplyDelete
  2. it's not working for me, AlarmReceiver is never being called. What am I doing wrong? I did refister receiver in manifest, so.. what am i missing?

    ReplyDelete
  3. good one and nice

    if any one looking for Android Alarm Manager to set a Remainder with Notification and Sound
    Have a look
    http://clearosapps.blogspot.in/p/android.html

    ReplyDelete
  4. public static class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current time as the default values for the picker
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
    DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Do something with the time chosen by the user

    Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, 10);

    Date d = c.getTime();

    long firstTime = c.getTimeInMillis() ;


    //long mytime = hourOfDay * 3600*1000 + minute*60*1000+ firstTime;


    //
    // if( view.is24HourView()){
    //
    // }

    // mytime+=firstTime;
    // Toast.makeText(getActivity(), "firstTime" + String.valueOf(firstTime) ,Toast.LENGTH_LONG).show();

    Context c1 = getActivity();


    Toast.makeText(getActivity(), "firstTime" + String.valueOf(firstTime) ,Toast.LENGTH_LONG).show();


    AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, firstTime, PendingIntent.getBroadcast(getActivity(),
    0, new Intent(getActivity(), MyReceiver.class), 0));



    }
    }
    }

    ReplyDelete
  5. I don't know how to not overwrite the existing alarm.please guide me

    ReplyDelete
    Replies
    1. Please check the following link:
      http://stackoverflow.com/questions/4212824/identify-and-cancel-an-alarm-send-to-an-alarmmanager

      Delete
  6. error on method "setLatestEventInfo();"

    ReplyDelete
    Replies
    1. you have to open your build manifest and set the target version, build version, and appcompactversion to 22

      Delete