2012-04-24 82 views
1

我有一個相當基本的應用程序,只有兩個活動,進入MainActivity的啓動畫面。我用固定的時間創建了一個使用AlarmManager觸發的通知。現在我在啓動畫面中執行AlarmManager。我有兩個問題。 一個:由於AlarmManger處於啓動活動狀態,它會在每次啓動應用程序時執行。所以如果通知時間已過,應用程序立即發送通知。 兩個:如果還沒有發生通知的時間,應用程序崩潰,因爲在MainActivity中我有一個調用來清除通知,並且由於通知尚未觸發,清除通知的調用會崩潰主要活動。我知道這是明顯的通知調用,導致MainActivity崩潰,因爲如果我將這個調用評論出來,應用程序運行良好。Android通知問題

問題:有沒有一種方法來編寫通知,以便在每次啓動應用程序時都不加載?我可以寫清楚通知位,以便它不會使應用程序崩潰,如果它沒有解僱?下面是這是在初始活動通知:

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")); 

回答

1

我猜你需要保存是否報警已設置狀態。僞代碼:

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塊的第二個問題:

try { 
    nm.cancel(getIntent().getExtras().getInt("uID")); 
} catch (Exception e) { 
    System.out.println("Error when cancelling: "+e.toString()); 
} 

另外,我剛纔注意到,至少你的示例代碼會產生一個NullPointerException,你是不是初始化NotificationManager類。

+0

Thanks ZeroOne。我會給你建議一個嘗試。我確實啓動了通知管理器,但是當我包含上述代碼時,我沒有包含那一點。 – kirktoon1882 2012-04-24 22:37:53

+1

ZeroOne - try-catch塊的工作原理。 Groovy的!至於我的第一個問題,我所做的是添加alCal.add(Calendar.DAY_OF_YEAR,1);所以明天就會開火,而且這似乎奏效了。今天早上它開了很好。我們將看到明天會發生什麼。謝謝您的幫助! – kirktoon1882 2012-04-25 16:38:57