user3824114
user3824114

Reputation: 105

Alarm from AlarmManager is not going off

With this code I am setting an alarm in onCreate of my MainActivity using the AlarmManager:

Intent startServiceIntent = new Intent(this, MyService.class);
AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, startServiceIntent, 0);

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 47);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 28);

manager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000, pendingIntent);

And the code of MyService is:

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show();
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), "Service Working", 1).show();
        return super.onStartCommand(intent, flags, startId);
    }
}

But none of the Toasts from MyService are shown? Can anybody tell me what I'm doing wrong?

Upvotes: 0

Views: 145

Answers (1)

Xaver Kapeller
Xaver Kapeller

Reputation: 49797

I assume the problem is here:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 47);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 28);

You are setting the calendar to the 28th August 2014 7:47 AM. So that would be in a month from now... The cause of this problem is here:

cal.set(Calendar.MONTH, 07);

Months in a Calendar are zero-based:

 0 -> January
 1 -> Febuary
 2 -> March
 3 -> April
 4 -> May
 5 -> June
 6 -> July
 7 -> August
 8 -> September
 9 -> October
10 -> November
11 -> December

So if you want to set the date to something in July you need to do it like this:

cal.set(Calendar.MONTH, 6);

Also try adding spaces around operators and after commas, makes your code a million times more readable. Oh and some proper indention would also be nice. I already fixed your code formatting this time.


EDIT:

The alarm is repeating because you are setting a repeating alarm with setRepeating(). If you want the alarm to go off only once then you just need to call set() instead, like this:

AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

Upvotes: 1

Related Questions