2011-08-20 98 views
1

我有一個IntentService類,我想用戶使用一個鬧鐘使服務每X小時執行一定的任務。AlarmManager啓動服務不工作

我檢索警報並設置它,但服務每2秒執行一次任務,而不是每隔X小時;它永遠不會停止:BroadcastReceiver總是觸發Intent

這是代碼:

@Override 
    protected void onHandleIntent(Intent intent) { 
     int alarmType = AlarmManager.RTC_WAKEUP; 
     username = intent.getStringExtra("username"); 
     //android.os.Debug.waitForDebugger(); 
     alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     context = getApplicationContext(); 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
     serviceToStart = intent.getStringExtra("serviceToStart"); 

     if (serviceToStart.equals("calls")) { 
      String CALLS_ALARM_ACTION = "ACTION_CALLS_LOGGING"; 
      Intent callsIntentToFire = new Intent(CALLS_ALARM_ACTION); 
      callsIntentToFire.putExtra("serviceToStart", serviceToStart); 
      callsAlarmIntent = PendingIntent.getBroadcast(context, 0, callsIntentToFire, 0); 
      callsUpdatefrequency = toLong(Integer.parseInt(prefs.getString(Preferences.CALLS_FREQUENCY_PREF, "0"))); 
      long callsTimeToUpdate = SystemClock.elapsedRealtime() + callsUpdatefrequency; 
      alarms.setRepeating(alarmType, callsTimeToUpdate, callsUpdatefrequency, callsAlarmIntent); 
      dumpCallsLog(); 

最後一個方法(dumpCallsLog())是更新一個遠程DB的方法。 有什麼我失蹤或代碼中不正確?

這是我的BroadcastReceiver代碼:

public class LoggingReceiver extends BroadcastReceiver { 
    public static final String ACTION_CALLS_LOGGING = "ACTION_CALLS_LOGGING"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent startIntent = new Intent(context, LoggingService.class); 
     String action = intent.getStringExtra("serviceToStart"); 
     startIntent.putExtra("serviceToStart", action); 
     context.startService(startIntent); 
    } 
} 
+0

'callsUpdatefrequency'是以毫秒錶示的嗎?爲什麼默認值是'0'? – CommonsWare

+0

@CommonsWare well'callsUpdateFrequency'現在使用調試值50000(應該是毫秒?),默認值是我的不好,因爲它應該是以毫秒錶示的一個小時。不過,那是我的基本代碼;剩下的時間我正在試着想出問題的解決方案(還沒找到) – noloman

回答

1

完成!我的不好:

String CALLS_ALARM_ACTION = "ACTION_CALLS_LOGGING"; 
        Intent callsIntentToFire = new Intent(CALLS_ALARM_ACTION); 

        callsIntentToFire.putExtra("serviceToStart", "dumpCalls"); 
        callsIntentToFire.putExtra("username", username); 

        callsAlarmIntent = PendingIntent.getBroadcast(context, 0, callsIntentToFire, 0); 

        callsTriggerAlarmTime = AlarmManager.ELAPSED_REALTIME_WAKEUP; 

        long callsAlarmInterval = 30000L; 
        // toLong(Integer.parseInt(prefs.getString(Preferences.CALLS_FREQUENCY_PREF, 
        // "86400000"))); 

        alarms.setRepeating(alarmType, callsTriggerAlarmTime, 
          callsAlarmInterval, callsAlarmIntent);