androidbroadcastreceiveralarmmanagernotificationmanagerandroid-reboot

Set alarms after rebooting Phone


I have a little question. I set my notifications in specific times using AlarmManager. The times I set notifications for are stored in SQLLite database. They all work perfect except the moment I reboot the phone. alarmManager looses their repeatings of course.

I would like to ask what is the best solution in this situation? I have my alarmManager set in MainActivity and I set my notification inside BroadcastReceiver as you can see in the code below:

Here is how I call it from MainActivity:

        Intent intent = new Intent(context, MyReceiver.class);
        intent.putExtra(EXTRA_TITLE, title);
        intent.putExtra(EXTRA_COUNT, count);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, count, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), WEEK_LENGTH_MS, pendingIntent);

And here is Broadcast Receiver's method onReceive

  public void onReceive(Context context, Intent intent)
    {
        nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        CharSequence from = context.getString(R.string.app_name);
        CharSequence message = intent.getStringExtra(DayActivity.EXTRA_TITLE);
        Intent intentNotification = new Intent(context,DayActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, intent.getIntExtra(DayActivity.EXTRA_COUNT,0), intentNotification, 0);
        Notification notif = new Notification(R.drawable.notification_logo,context.getString(R.string.app_name), System.currentTimeMillis());
        notif.setLatestEventInfo(context, from, message, contentIntent);
        notif.defaults |= Notification.DEFAULT_LIGHTS;
        notif.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        nm.notify(intent.getIntExtra(DayActivity.EXTRA_COUNT,0), notif);

    }

I am declaring BroadcastReceiver for BOOT_COMPLETED event, but it always calls just empty notification at the time i start the phone and never more.


Solution

  • I would like to ask what is the best solution in this situation?

    Register a BOOT_COMPLETED BroadcastReceiver to call setRepeating() on AlarmManager to re-establish your schedules.

    I am declaring BroadcastReceiver for BOOT_COMPLETED event, but it always calls just empty notification at the time i start the phone and never more.

    The objective of the BOOT_COMPLETED BroadcastReceiver should be to reschedule your alarms. You might wish to consider using a separate BroadcastReceiver than the one you are using for the alarm events themselves.