2015-10-15 106 views
2

我想讓Alarmmanager在2秒後首次觸發,然後每隔10秒觸發一次。Alarmmanager第一次觸發但不重複

2秒後它不會第一次開火。 5到10秒之後。它根本不重複。

這裏是我的代碼:

Alarmmanager:

Intent intent = new Intent(this, BackgroundService.class); 
final PendingIntent pendingintent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0); 

final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + 2 * 1000, 10 * 1000, pendingintent); 

清單:

<receiver android:process=":remote" android:name=".BackgroundService"/> 

BackgroundService.java:

public class BackgroundService extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("BackgroundService", "BackgroundService onReceive"); 
    } 
} 
+1

儘量不要使用AlarmManager類。 – Owner

+0

還有什麼?那麼爲何不? – Michael

+0

Intent i = new Intent(AlarmClock.ACTION_SET_ALARM); – Owner

回答

3

明白了:

的IDE說:第三屆值將被強制高達60000(1分鐘),以節省電池。但我從未等過這麼久,所以看起來它甚至沒有重複。

Snap is here

1
am.setRepeating(AlarmManager.RTC_WAKEUP, **cal_alarm.getTimeInMillis()**, 1000*60*5 , pendingIntent); 

我想你正在使用System.currentTimeMillis(),因爲你有這個問題。嘗試從您設置了鬧鐘的代碼中獲取時間。上述代碼中的第三個參數是重複時間。你可以將它設置爲10秒。

+0

我將它改爲:'Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND,2); alarmManager.setRepeating(AlarmManager.RTC,calendar.getTimeInMillis(),2000,pendingintent);' 同樣的結果 – Michael

+0

Date dat = new Date(); 日曆cal_alarm = Calendar.getInstance(); 日曆cal_now = Calendar.getInstance(); cal_now.setTime(dat); cal_alarm.setTime(dat); cal_alarm.set(Calendar.HOUR_OF_DAY,10); cal_alarm.set(Calendar.MINUTE,43); cal_alarm.set(Calendar.SECOND,0); – Owner

+0

我的意思是你爲鬧鐘設定的時間,因爲你想讓鬧鐘設置爲早上5點半。將cal_alarm設置爲該值。 – Owner

0

這heslp我

if (android.os.Build.VERSION.SDK_INT >= 19) { 
       alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
      } else { 
       alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
      }