Search code examples
androidbroadcastreceiver

Re-scheduling Alarms after device reboot


I have a BroadcastReceiver which is supposed to re-schedule AlarmManager's Alarms after device reboots. After reboot onReceive() method is triggered (I can see Log.v output in the logcat) but the rest of the code doesn't re-schedule any alarms. Maybe there is something wrong with it but logcat shows only this:

logcat:

11-25 15:51:17.680    2192-2212/system_process I/ActivityManager﹕ Start proc com.example.app for broadcast com.example.app/.BReceiver: pid=3668 uid=10080 gids={50080, 3003, 1015, 1028}
11-25 15:51:25.570    2192-2203/system_process I/ActivityManager﹕ No longer want com.example.app (pid 3668): empty #17

Receiver:

public class BReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    Log.v("BOOT_COMPLETED", "RECEIVED"); // this is logged

    DBScheduledRecords dbrec = new DBScheduledRecords(context);
    Cursor cur = dbrec.selectAllRecords();
    cur.moveToFirst();

    while(cur.moveToNext()) {
        int duration = cur.getInt(5);
        String link = cur.getString(1);
        int randomInt = cur.getInt(6);
        Long start = cur.getLong(8);

        Calendar today = Calendar.getInstance();   // current instance

        if (today.getTimeInMillis() > start) {
            start = start + (AlarmManager.INTERVAL_DAY * 7);
        }


        long lDuration = Long.parseLong(String.valueOf(duration * 60000));
        Intent startIntent = new Intent(context, WakefulReceiver.class);

        //  startIntent.setAction("ALARM");
        startIntent.putExtra("httpAddress", link);
        startIntent.putExtra("millis", lDuration);
        startIntent.putExtra("startInMillis", start);
        startIntent.putExtra("randomInt", randomInt);


        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, randomInt, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, start, pendingIntent);


    }

}
}

Solution

  • As it revealed there was a few problems here, but the reason of having "no effect" in the logcat was caused by: while(cur.moveToNext()) plus the fact I had only one row in my database (cursor poitner was already behind only row in the DB after calling moveToNext()). Now I'm using:

    while(cur.getCount() > cur.getPosition()) {
      //
      cur.moveToNext();
    }
    

    In the meantime (while I was thinking of the reason of such behavior) I moved the code to the IntentService as @CommonsWare suggested.

    Thanks for your comments. This was really helpful.