Issue in setting alarm time in AlarmManager Class

Posted by Anshuman on Stack Overflow See other posts from Stack Overflow or by Anshuman
Published on 2012-07-09T09:12:37Z Indexed on 2012/07/09 9:15 UTC
Read the original article Hit count: 302

Filed under:

I have used the following code in setting alarm time in AlarmManager class. Now Suppose my device current date 9-july-2012 11:31:00, Now suppose i set set a alarm at 9-july-2012 11:45:00, then it works fine and pop-up an alarm at that time. But if i set an alarm at 10-aug-2012 11:40:00, then as soon as exit the app the alarm pop-up, which is wrong because i set an alarm at month of august, So why this happen, is anything wrong in my code. if anyone knows help me to solve this out.

Code For Setting Alarm time in AlarmManager class

Intent myIntent = new Intent(context, AlarmService.class); 
PendingIntent pendingIntent = PendingIntent.getService(context, i, myIntent, i); 
AlarmManager alarmManager = (AlarmManager)context.getSystemService(AlarmService.ALARM_SERVICE); 

Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(System.currentTimeMillis()); 
calendar.add(Calendar.MILLISECOND, (int) dateDifferenceFromSystemTime(NoteManager.getSingletonObject().getAlarmTime(i))); 
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 

public static long dateDifferenceFromSystemTime(Date date) 
{
    long difference = 0;
    try 
    {
        Calendar c = Calendar.getInstance();
        difference = date.getTime() - c.getTimeInMillis();
        if (difference < 0) 
        {
            // if difference is -1 - means alarm time is of previous time then current
            // then firstly change it to +positive and subtract form 86400000 to get exact new time to play alarm
            // 86400000-Total no of milliseconds of 24hr Day
            difference = difference * -1;
            difference = 86400000 - difference; 
        }
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    return difference;
}

Service class which pop-up alarm when matches time

public class AlarmService extends IntentService 
{       
public void onCreate() 
{
    super.onCreate();
}

public AlarmService() 
{
    super("MyAlarmService");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    super.onStartCommand(intent, startId, startId);
    return START_STICKY;
}

@Override
protected void onHandleIntent(Intent intent) 
{   
    startActivity(new Intent(this,AlarmDialogActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}       
}

© Stack Overflow or respective owner

Related posts about android