Frage

I am registering an Alarm manager in the onResume() state in my MainActivity.java (which is the main activity where the program start)

protected void onResume() {
    super.onResume();
    if (Helper.isNetworkAvailable(this)) {
        Intent intent = new Intent(this, NewsIntentService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
                10 * 60 * 1000, pi);
    } else {
        // nothing done
    }
}

However I was getting inconsistent results, the following code runs good and with no errors, it shows that the PendingIntent should be fired at every 10 minutes but the results where on the following from logcat for example:

It starts working good:

2:00 pm (fired), 2:10 pm (fired), 2:30 pm (fired), ...

But after some time:

3:20 pm (fired), 3:27 pm (fired), 3:33 pm (fired), 3:38 pm (fired) ...

The question is at what life cycle of the activity it is best to register an AlarmManager and if what I did is correct what is the reason for the inconsistent run.

War es hilfreich?

Lösung

use the following code it worked for me:

1- private SharedPreferences prefs;

2-

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Launch SharedPreferences
        prefs = getSharedPreferences("Alarm", MODE_PRIVATE);

3-

protected void onResume() {
        super.onResume();

        if(!prefs.getBoolean(Helper.ALARM_SET, false)) {
            Intent intent = new Intent(this, NewsIntentService.class);
            PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
                    10 * 60 * 1000, pi);

            Log.i(Helper.ALARM_SET, "Alarm is set.");

            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean(Helper.ALARM_SET, true);
            editor.commit();
        }   
    }

Explanation:

The Use SharedPreferences to save a boolean value AlARM_SET, simple precise and this code will work even if the phone has restarted or turned off.

Andere Tipps

Your onResume is getting called at those times, hence triggering the alarm and once again setting it for next ten minutes.

If your end result is to invoke a functionality on Alarm, try to set the next alarm there, call your alarm once in onCreate of your MainActivity.(Check for the first run, use a File for the same or just Shared Preference) Let the rest be handled by the service/function/code which is run upon triggering the alarm.

Check here for complete implementation.

The flow would be something like:

MainActivity--> onCreate--> Check if first run--> Yes--> Register Alarm and execute immediately--> Invoke function/code-->Let this code set the next alarm.

The docs for AlarmManager clearly state that repeating alarms are inexact -- hence the drift you observe via Logcat.

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

A block of the code that you can use:

public void schedule(final Context context) {

    int alarmCode = YOUR_ALARM_CODE;
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, alarmCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    final Calendar calendar = yourCalendar();

    final AlarmManager alarm = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);

    final long time = calendar.getTimeInMillis();

    alarm.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top