Reminder Notifications Problem after Android Phone Reboot

AttilaB
AttilaB used Ask the Experts™
on
I am creating an Android application that allows users to add notes, organize them into categories, and set reminders for the notes in the form of push notifications.

I am able to schedule reminder notifications when the phone is on. However, if you turn the phone off and then turn it on later, or restart it, then set multiple notifications: one that has a scheduled time after the phone has been rebooted or turned on again and one that is scheduled to go off at a time after the phone has been rebooted or turned off, then both notifications go off immediately after the phone turns on or is rebooted.

The expected behavior is that the notification that is scheduled at a time after the phone has rebooted fires at the scheduled time instead of right away.

Please see RebootReceiver.java and NotificationScheduler.java below and let me know if you need additional files from my project or information.

RebootReceiver Class:

package com.coolcoderz.notes2go;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static android.content.Context.ALARM_SERVICE;


public class RebootReceiver extends BroadcastReceiver {

    String TAG = "RebootReceiver";
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    private DatabaseHelper dbHelper;

    @Override
    public void onReceive(Context context, Intent intent) {
        dbHelper = new DatabaseHelper(context);

        if ((intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))) {

            Toast.makeText(context, "REBOOT", Toast.LENGTH_LONG).show();

            Log.d(TAG, "onReceive: ");

            dbHelper = new DatabaseHelper(context);

            NotificationScheduler notificationScheduler = new NotificationScheduler();

            List<Category> categories = dbHelper.getAllCategories();
            String category = "";
            for (Category c : categories) {
                category = c.getCategoryName();
                List<NoteCategory> noteCategories = dbHelper.getAllNoteCategories(category);
                for (NoteCategory n : noteCategories) {
                    if (n.getIsReminderActive() == 1) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(n.getDateTime());

                        if (calendar.getTimeInMillis() >= Calendar.getInstance().getTimeInMillis()) {
                            notificationScheduler.setReminder(context, RebootReceiver.class, calendar, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE));
                            notificationScheduler.showNotification(context, MainActivity.class,
                                    "Notes2Go Reminders", n.getDescription());
                            n.setIsReminderActive(0);
                            dbHelper.updateNote(n);

                        } else {

                            notificationScheduler.setReminder(context, RebootReceiver.class, Calendar.getInstance(), Calendar.getInstance().get(Calendar.HOUR), Calendar.getInstance().get(Calendar.MINUTE));
                            notificationScheduler.showNotification(context, MainActivity.class,
                                    "Notes2Go Reminders", n.getDescription());
                            n.setIsReminderActive(0);
                            dbHelper.updateNote(n);

                        }
                        if (MainActivity.listAdapter != null && MainActivity.expListView != null) {
                            MainActivity.listAdapter.notifyDataSetChanged();
                            MainActivity.expListView.refreshDrawableState();
                            MainActivity.expListView.invalidateViews();
                        }

                    }


                }
            }
        }
    }
}

Open in new window



NotificationScheduler Class:

package com.coolcoderz.notes2go;


import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;

import java.util.Calendar;

import static android.content.Context.ALARM_SERVICE;


public class NotificationScheduler {

    public void setReminder(Context context, Class<?> cls, Calendar c, int hour, int min) {

        Calendar setcalendar = c;
        setcalendar.set(Calendar.HOUR_OF_DAY, hour);
        setcalendar.set(Calendar.MINUTE, min);
        setcalendar.set(Calendar.SECOND, 0);

        setcalendar.add(Calendar.DATE, c.get(Calendar.DATE));

        Toast.makeText(context, String.valueOf(c.getTimeInMillis()), Toast.LENGTH_SHORT).show();


        // Enable a receiver

        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);


        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) c.getTimeInMillis(), intent1, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);


        if (Build.VERSION.SDK_INT < 19)
            am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 1000, pendingIntent);
        else
            am.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 1000, pendingIntent);


    }

    public void showNotification(Context context, Class<?> cls, String title, String content, Calendar c) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        long[] vibrateDuration = {0, 1000, 2000, 3000};
        int random = (int) c.getTimeInMillis();

        Intent notificationIntent = new Intent(context, cls);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(cls);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(random, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        Notification notification = builder.setContentTitle(title)
                .setContentText(content)
                .setOnlyAlertOnce(true)
                .setSound(alarmSound)
                .setSmallIcon(R.mipmap.n2g_icon)
                .setVibrate(vibrateDuration)
                .setContentIntent(pendingIntent).build();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(random++, notification);

    }

}

Open in new window


Thank you for your help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial