Question

I'm attempting to start up a Background IntentService that will run every minute. I want to start this Service after the user logs into my app for the first time, so I have my code here:

This code will only be called after the user logs in:

public class MainMenuActivity extends SingleFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);

    // This is reached after logging in, so we are setting alarm on login
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isOn = prefs.getBoolean(GPSTracker.PREF_IS_ALARM_ON, false);
    GPSTracker.setServiceAlarm(this, true);// TODO: Always setting this to true, not sure if we should be
}

Then I have this code in my GPSTracker which extends IntentService:

 private static final int POLL_INTERVAL = 1000  * 60 * 1;// 1 minute

public static void setServiceAlarm(Context context, boolean isOn) {
    Intent i = new Intent(context, GPSTracker.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if(isOn) {
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), POLL_INTERVAL, pi);// TODO: Is AlarmManager.ELAPSED_REALTIME what I want!?
    } else {
        alarmManager.cancel(pi);
        pi.cancel();
    }

    PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(GPSTracker.PREF_IS_ALARM_ON, isOn).commit();
}


@Override
protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "In onHandleIntent");
}

However, my onHandleIntent is never called, and I never see anything in LogCat.

Was it helpful?

Solution

You are using AlarmManager.ELAPSED_REALTIME with System.currentTimeMillis(). That is an invalid combination.

Either:

  • Use AlarmManager.RTC with System.currentTimeMillis(), or

  • Use AlarmManager.ELAPSED_REALTIME with SystemClock.elapsedRealtime()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top