2017-03-10 61 views
0

我正在使用鬧鐘管理器來呼叫api。它在onCreate活動中被調用。我希望它在應用程序啓動時調用鬧鐘,然後每三小時報警一次。AlarmManager即使沒有時間也會重複呼叫

Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(System.currentTimeMillis()); 
    calendar.set(Calendar.HOUR_OF_DAY,1); 
    AlarmManager alarmManager1 = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
    Intent myIntent1 = new Intent(LobbyActivity.this,WeatherBroadCastReceiverCurrent.class); 
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this,0,myIntent1,0); 

    alarmManager1.setInexactRepeating(AlarmManager.RTC,calendar.getTimeInMillis(),AlarmManager.INTERVAL_HOUR+ 
      AlarmManager.INTERVAL_HOUR+AlarmManager.INTERVAL_HOUR/*(1000*60*60*3)*/,pendingIntent1); 

然後,當點擊一個按鈕時,該活動結束並進行到另一活動。我的問題是,如果活動重新創建,即使不是時間,也會調用警報。我可以在非活動類別上設置鬧鐘,以便在重新創建活動時不會被召回?如果是的話如何? Tia

回答

0

嘗試通過刪除運行calendar.set(Calendar.HOUR_OF_DAY,1);並運行,它會在應用程序啓動時調用報警

+0

謝謝你的回答,但我的問題是警報正在觸發,每當我宣佈警報的活動重新創建。我需要的是在鬧鐘設置後,它會觸發一次,每3小時打一次電話。會發生什麼,即使沒有時間,活動重新創建後也會再次觸發。 – John

+0

你可以存儲靜態值prefrence來檢查應用程序是否第一次運行或不基於你可以設置我看到的報警 –

+0

。非常感謝你。 – John

0

要簡單地克服這個問題,您需要創建一個標誌並將其設置爲true,以便活動可以檢查報警是否已經設置過,那麼它將前進而不設置它。

使用SharedPreferences對此非常理想。 這是我的一個片段,根據您的需要進行編輯。

SharedPreferences prefs; 
SharedPreferences.Editor ed; 
prefs = PreferenceManager.getDefaultSharedPreferences(this); 
ed = prefs.edit(); 
boolean isOpeningForTheFirstTime = prefs.getBoolean("firstTime", true); 

if(!isOpeningForTheFirstTime) { 
    Intent i = new Intent(this, StartScreen.class); 
    startActivity(i); 
    finish(); 
} 

而AlarmManager可以通過刪除一些東西來簡化。

public void setAlarm(){ 

    //To get the current time 
    long alertTime = new GregorianCalendar().getTimeInMillis(); 

    //Interval of a minute 
    int timeInterval = 60000; 

    //Intent which you want to start 
    Intent alertIntent = new Intent(this, ClassName.class); 

    //Declaring the alarmManager 
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

    //Setting the alarmmanager up. 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, timeInterval, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); 
} 
+0

感謝您的答案!它幫助了很多人歡呼 – John

相關問題