Question

in my application I have set the notification inside onCreate() of launcher activity. I am getting result successfully but as it is written inside the onCreate it is showing notification every time I launch app also. How should I resolve this, I want the notification only on given time. Below is the code I am using :-

Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 49);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.PM);

        Intent myIntent = new Intent(Main.this, MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(Main.this, 0, myIntent,0);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
Was it helpful?

Solution

Create a new method and call the method when you want your notification to launch.

public void showNotification() {

Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 49);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.PM);

        Intent myIntent = new Intent(Main.this, MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(Main.this, 0, myIntent,0);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

}

Now when you want to call this method simple write:

showNotification();

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top