Hiren Hiren - 1 year ago 69
Android Question

Local Notification trigger everytime when opening application

I have to trigger a local notification at 5:30AM and that is working. But the problem is the notification is also getting triggered whenever I open my application. Here is my code in my

MainActivity
:

in my
onCreate()
of
MainActivity
:

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 5);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);


Here is my
MyStartServiceReceiver
:

public class MyStartServiceReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Log.e("AlarmReceiver", "Started");
Intent intent1 = new Intent(context, AlarmService.class);
intent1.setData(Uri.parse("custom://" + System.currentTimeMillis()));
context.startService(intent1);
}
}


Why is it triggering everytime I am opening my application?

Answer Source

You are setting alarm current date 5:05AM, if it is already passed alarm will be triggered immediately. To stop it do like this.

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 5);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

What we are doing here is, if time already passed we are adding date by +1 so it will start from next date and we are cancelling previous set alarm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download