I want set the alarm at the specified time and implement the notification at the specified time(in a day) by using BroadcastReceiver and AlaramManager.
It alarmed specified time. After when I run the app, it again alarm even though it's not the time I set.
In other words, when I set the alarm 9:21 pm and I run the app after 9:21 pm, the notification is generated.
I just want to make the alarm notification at the specified time I set and app doesn't run. Also, when I run the app, it doesn't alarm.
How can I fix it?
This is my BroadcastReceiver Code -
public class BroadcastD extends BroadcastReceiver{
Context context;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
showNotification();
}
public void showNotification() {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent
.getActivity(context, 0, new Intent(context, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setTicker("Ticket")
.setContentTitle("Title")
.setContentText("Context")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
notificationManager.notify(1, builder.build());
}
}
This is my MainActivity code :
public class MainActivity extends AppCompatActivity {
AlarmManager am ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
AlarmHATT alarmHATT = new AlarmHATT(getApplicationContext());
alarmHATT.Alarm();
}
public class AlarmHATT {
private Context context;
public AlarmHATT(Context context) {
this.context = context;
}
public void Alarm() {
Intent intent = new Intent( context.getApplicationContext(), BroadcastD.class);
PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DATE), 21, 21, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, sender);
}
}
To avoid having the alarm fire immediately, configure your start time with the
Calendar
like this:And then if the time you are setting has already passed today, you need to set the calendar to the following day with:
That will avoid having your alarm fire immediately because it was set to a time that already passed earlier in the day.
Then continue to use
calendar.getTimeInMillis()
as your starting time.