Search code examples
androidandroid-notificationsandroid-alarms

how to schedule a notification using alarm manager


I have defined a receiver which should fire the notification when it is called. This works only if I call the receiver straight away. I am unable to schedule it for a specific date.

Calendar c = Calendar.getInstance();
c.set(2014, 4, 18, 2, 20, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);   
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);

This is my Receiver class:

public class TimeAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent paramIntent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = new Intent("android.intent.action.VIEW");
    intent.setData(Uri.parse("http://www.sdfasdf.ch"));
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification
    Notification notification = new Notification(R.drawable.android_anydont_logo, "sdfs", System.currentTimeMillis());
    notification.setLatestEventInfo(context, "something something", "darkside",pendingIntent);

    // Fire the notification
    notificationManager.notify(1, notification);
}
}

This is the definition in the manifest:

receiver
        android:name="com.hack.doneit.utils.TimeAlarm"
        android:process=":remote" />

My problem is that i am unable to set the alarm to trigger the receiver at a specific time in the future. A specific day would be enough.


Solution

  • Problem is with the Month value you have set. I believe you thought for month April the value is 4. The value of month starts from 0 , so April will be 3.

    Change you code on month as Calendar.APRIL or set value as 3

    c.set(2014, Calendar.APRIL, 17, 20, 43, 0);
    

    This should work. Apart from this your codes are perfect.

    Note: Your using the Notification deprecated API's . Use Notification Builder