Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlarmManager alarm fires immediately

I'm testing AlarmManager to use in my app, and it is firing my Broadcast Receiver immediately when I want it to fire after 1 minute. The code is below:

public class SetMealTimersActivity extends Activity {
    PendingIntent pi;
    BroadcastReceiver br;
    AlarmManager am;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_meal_timers);

        br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent i) {
                Toast.makeText(c, "Ready to Go!", Toast.LENGTH_LONG).show();
            }
        };
        registerReceiver(br, new IntentFilter("com.ian.mealtimer"));
        pi = PendingIntent.getBroadcast(this, 0, new Intent(
                "com.ian.mealtimer"), 0);
        am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));         
        am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 
                60 * 1000, pi );
    }
like image 542
Ian M Avatar asked Jun 02 '14 12:06

Ian M


2 Answers

try :

  am.set(AlarmManager.RTC_WAKEUP, 
      Calendar.getInstance().getTimeInMillis()+60*1000, pendingIntent);

it is working for me.

like image 97
Eliott Roynette Avatar answered Nov 16 '22 19:11

Eliott Roynette


If using an exact alarm, make sure it's time is in the future. Otherwise it will fire immediately.

like image 32
Daniel Wilson Avatar answered Nov 16 '22 18:11

Daniel Wilson