我有一个相当基本的应用程序,它只有两个 Activity ,进入 MainActivity 的初始屏幕。我创建了一个固定时间的通知,它使用 AlarmManager 触发。现在,我在启动画面期间执行了 AlarmManager。我有两个问题。 一:由于AlarmManger 在splash Activity 中,每次启动应用程序时都会执行。因此,如果通知时间已过,应用程序会立即发送通知。 二:如果通知时间还没有到,应用程序崩溃,因为在 MainActivity 中我有一个清除通知的调用,并且由于通知还没有触发,调用清除通知会使 MainActivity 崩溃。我知道是明确的通知调用导致 MainActivity 崩溃,因为如果我评论调用,应用程序运行正常。
问题:有没有一种方法可以对通知进行编码,使其不会在每次启动应用程序时都加载?我可以写清楚通知位,这样如果应用程序没有被触发它就不会崩溃吗?这是 Splash Activity 中的通知:
private void launchAlarmManager() {
//---- ALARM MANAGER ------
//---use the AlarmManager to trigger an alarm---
AlarmManager aMan = (AlarmManager) getSystemService(ALARM_SERVICE);
//---get current date and time---
Calendar alCal = Calendar.getInstance();
//---sets the time for the alarm to trigger---
alCal.set(Calendar.HOUR_OF_DAY, 12);
alCal.set(Calendar.MINUTE, 25);
alCal.set(Calendar.SECOND, 00);
//---PendingIntent to launch activity when the alarm triggers---
Intent iDN = new Intent("com.myapp.DISPLAYNOTIFICATIONS");
PendingIntent pendA = PendingIntent.getActivity(this, 0, iDN, 0);
//---sets the alarm to trigger---
aMan.set(AlarmManager.RTC_WAKEUP, alCal.getTimeInMillis(), pendA);
//---- END ALARM MANAGER ------
这是 MainActivity 中的取消通知位:
NotificationManager nm;
//---cancel the notification by getting the Unique ID from the DisplayNotification class---
nm.cancel(getIntent().getExtras().getInt("uID"));
最佳答案
我想你需要保存闹钟是否已经设置的状态。在伪代码中:
load the alarm_has_been_set variable
if( !alarm_has_been_set ) {
set alarm
save alarm_has_been_set = true
}
然后,一旦警报触发,您就取消设置该变量。有关保存和加载,请参阅 Making data persistent in Android .
关于取消通知时崩溃的第二个问题,请尝试使用 try-catch block :
try {
nm.cancel(getIntent().getExtras().getInt("uID"));
} catch (Exception e) {
System.out.println("Error when cancelling: "+e.toString());
}
此外,我刚刚注意到至少您的示例代码会产生 NullPointerException,因为您根本没有初始化 NotificationManager 类。
关于安卓通知问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306138/