简体   繁体   中英

Facing notification problems in android using Alarm manager

So I'm trying to send a notification to the user everyday in the morning at around 10 am. The user has the option to cancel the daily notification.

I'm facing some issues. I throw a notification at 10 am. I'm receiving it. However, it throws another notification a few seconds or minutes later. I'm trying to set up this notification in a separate runnable thread. I'm able to successfully implement the cancel option but I am facing this multiple notification issue. Here I'm attaching the part of the code:

class Signup implements Runnable {

    @Override
    public void run() {
        Calendar updateTime = Calendar.getInstance();
        updateTime.set(Calendar.HOUR_OF_DAY, 10);
        updateTime.set(Calendar.MINUTE, 03);
        updateTime.set(Calendar.SECOND,10);

        Intent notification = new Intent(MainActivity.this, Alert.class);
        PendingIntent recurringNotification = PendingIntent.getBroadcast(MainActivity.this,
                0, notification, PendingIntent.FLAG_CANCEL_CURRENT);



        AlarmManager alarms = (AlarmManager) MainActivity.this.getSystemService(
                Context.ALARM_SERVICE);
        alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringNotification);
    }
}

Receiver :

public class Alert extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        dailyNotif(context,"title","Your Notif is here. Click to view.", 
             " here.");

    }
    public void dailyNotif(Context context, String title, String body, String alert){

        Intent notifyIntent = new Intent(context,AnotherNotif.class);
        PendingIntent notification = PendingIntent.getActivity(context,0,notifyIntent,0);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle(title)
                                    .setTicker(alert)
                                    .setContentText(body);

        builder.setContentIntent(notification);
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
        builder.setAutoCancel(true);
        context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());

    }


}

Figured out why it was throwing a random notification.

If the time is already passed , It'll throw a notification right when you run the application. So in that case you need to add a day to your alarm time if

current time > alarm time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM