Neo
Neo

Reputation: 16239

How do I set notification in android application at specific time?

I have used following code in android application to set up Notification(Alarm) using AlarmManager.

 public void setAlarm() {
          Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
          PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);

          am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            (40000), pendingIntent);
         }

Or should I use following code

   Calendar calendar = Calendar.getInstance();

      calendar.set(Calendar.MONTH, 3);
      calendar.set(Calendar.YEAR, 2015);
      calendar.set(Calendar.DAY_OF_MONTH, 21);

      calendar.set(Calendar.HOUR_OF_DAY,11);
      calendar.set(Calendar.MINUTE, 15);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.AM_PM,Calendar.AM);

      Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

I want to set (notification)alarm at this specific time : 11:15AM on 21-March-2015

Can any one help me to set this?

Upvotes: 1

Views: 2055

Answers (3)

Apurva
Apurva

Reputation: 7911

Run one thread every second and compare your specified time with current time, and if matches set notification.

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm aa");
String dateTimeinSrting = "21-Mar-2015 11:15 am";

try {
    Date dateTime = formatter.parse(dateTimeInString);
} catch (ParseException e) {
    e.printStackTrace();
}

float dateTimeInMillis = dateTime.getTime();

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {

        Calendar calendar;

        if(Float.compare(dateTimeInMillis, calendar.getTimeInMillis())){
            //Set the notification here
        }

        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

Upvotes: 1

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16224

First you need to use Calendar to set your date something like:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.DAY_OF_MONTH, 15);

cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 15);

And then in your setAlarm() method you need to set the alarm only once. You don't need to repeat it so:

public void setAlarm() {
     Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);

     am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent);
}

Upvotes: 3

Related Questions