AlarmManager to start Service not working
I have an IntentService
class and I want to user an Alarm to make the service perform a certain task every X hours.
I retrieve the alarm and set it but the service performs its task every 2 seconds instead of every X hours; it's never stopping: the BroadcastReceiver
is always firing the Intent
.
This is the code:
@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 = 开发者_如何学CPendingIntent.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();
The last method (dumpCallsLog()) is the method that updates a remote DB. Is there anything I'm missing or that it's incorrect in the code?
This is my BroadcastReceiver
code:
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);
}
}
Done! My bad:
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);
精彩评论