在我的应用程序中,我在启动器活动的onCreate()中设置了通知。我成功地获得了结果但是因为它是在onCreate中写的,所以每次启动应用程序时它都会显示通知。 我应该如何解决这个问题,我只想在给定时间内通知。 以下是我正在使用的代码: -
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);
答案 0 :(得分:1)
创建新方法,并在希望启动通知时调用该方法。
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);
}
现在当你想调用这个方法时,简单写一下:
showNotification();
希望这有帮助。