atanti atanti - 2 months ago 16
Android Question

How to call AlarmManager method after AlarmManager fires?

I want to change the

Intent
extra with each fire of
AlarmManager
. Is this possible, how do I call
AlarmManager
as soon as it fires ?

Code:

public void startCollector(){
final int LOOP_REQUEST_CODE = 4;
Intent i = new Intent(getApplicationContext(), DataCollector.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(),LOOP_REQUEST_CODE,i,PendingIntent.FLAG_NO_CREATE);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 3*1000;
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//TO CHANGE INTENT EXTRAS DO NOT REMOVE.
if(sender != null){
am.cancel(sender);
}
if(getLocation() != null) {
i.putExtra("JLocation", getLocation());
}
i.putExtra("JLocation",getLocation());
sender = PendingIntent.getBroadcast(getApplicationContext(),LOOP_REQUEST_CODE,i,PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 100000, sender);
}

Answer

I'd suggest you to use an exact alarm instead of using setRepeating() and reschedule it every time it fires.

(setRepeating() does not work with Doze anyway)

For example:

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

// if you would like to fire the next alarm very precisely
// put this value in the Intent and use it in your receiver
// to calculate the next time for the alarm
long fireAt = SystemClock.elapsedRealtime() + 5000;

if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
} else if (Build.VERSION.SDK_INT > 19 && Build.VERSION.SDK_INT < 23) {
    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
} else if (Build.VERSION.SDK_INT > 23) {
    am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        fireAt, pendingIntent);
}

And in your receiver:

@Override
public void onReceive(Context context, Intent intent) {

    // change the Intent as you wish
    intent.putExtra("anExtra", "aValue");
    // or create a new one
    //Intent newIntent = new Intent(context, this.getClass());

    PendingIntent pendingIntent = PendingIntent
        .getBroadcast(context, 0, intent, 0);

    AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);

    long fireAt = SystemClock.elapsedRealtime() + 5000;

    if (Build.VERSION.SDK_INT < 19) {
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
    } else if (Build.VERSION.SDK_INT > 19 && Build.VERSION.SDK_INT < 23) {
        am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
    } else if (Build.VERSION.SDK_INT > 23) {
        am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        fireAt, pendingIntent);
    }
}
Comments