2014-12-02 53 views
1

我有一個服務,我想每天運行,所以檢查一些東西在我的數據庫,如果需要創建一個通知。 爲了每天運行我的服務,我使用了一個alarmManager,它第一次工作正常,但是一旦啓動,我的服務進入一個無限循環,我知道這是因爲alarmManager,因爲它只是進入循環當警報管理員啓動時。這裏是我的服務代碼:Android alarmManager進入循環

public class MyService extends Service { 

... 
    public MyService() { 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 



     checkMechanicUseer(); 

     this.stopSelf(); 


     return START_NOT_STICKY; 
    } 

    private void checkMechanicUseer() { 

    ... 

    } 




    @Override 
    public void onDestroy() { 
     super.onDestroy(); 



     final SharedPreferences settings = getSharedPreferences("MYSETTINGS",0); 
     int time = settings.getInt("time",9); 



     Calendar calNow = Calendar.getInstance(); 
     Calendar calSet = (Calendar) calNow.clone(); 

     calSet.set(Calendar.HOUR_OF_DAY, 9); 
     calSet.set(Calendar.MINUTE, 0); 
     calSet.set(Calendar.SECOND, 0); 
     calSet.set(Calendar.MILLISECOND, 0); // I want it to trigger at 09:00 am each day 

     AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE); 
     alarm.setRepeating(
       alarm.RTC_WAKEUP, 
       calSet.getTimeInMillis() ,(1000 * 60), 
       PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0) 
     ); // I set the (1000 * 60) so I can check it with 1 min interval, so I wont need to wait one day for it ... of course I need to change it to (1000 * 60 * 60 * 24) 

     Toast.makeText(MyService.this, "Service destroyed",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 



} 

我想我需要取消我的鬧鐘一些地方,然後設置另一個。但不知道如何或在哪裏做

仍然有問題,如果我有alarm.set改變alarm.setRepeat如下:

alarm.set(
       alarm.RTC_WAKEUP, 
       calSet.getTimeInMillis() + (1000 * 60), 
       PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0) 
     ); 

回答

1

我認爲,這是因爲你把鬧鐘調在過去的日期, 9點第一次發火,然後你重置9點鐘的鬧鐘,但這次是過去的,所以鬧鐘立即開火,你有一個很好的循環。

檢查時間是否不在過去,如果是,則在日曆中添加一天。

+0

這是問題,謝謝你。 但讓我說,如果我將間隔設置爲(1000 * 60 * 60 * 24),並設置校準小時,分鐘,秒和毫秒,第二個代碼(只有'alarm.set'將起作用won舉起了@Jivy發現的問題 – 2014-12-02 12:29:59

+0

這對我來說也是一個問題,我的函數檢查過去是否存在邏輯錯誤,並且讓AlarmManager進入了一個循環, 4秒鐘,你可以看到報警計劃使用'adb shell dumpsys alarm'的時間,並使用'-a'標誌爲你的應用程序名稱進行grep以獲取後面的行。 – 2017-06-24 02:02:09