Q:

postDelayed in BroadcastReceiver

I have got a BroadcastReceiver that is triggered at specific times (via AlarmManager). It is programatically scheduled, depending on the preferences set by the user.
The BroadcastReceiver does (simplified and pseudocode):
public void onReceive(Context context, Intent intent) {
  handler = new Handler();
  wifiManager.setWifiEnabled(true);
  // Wait a few seconds to activate wifi and get IP
  handler.postDelayed(new Runnable() {
    void run() {
      doTheJob();
    }
  }, 30000);
}

public void doTheJob() {
  doSomethingAndTheOther(); // this starts service: context.startService(i);
  wifiManager.setWifiEnabled(false);
}

I have used this code for several years in HTC Desire without problems. Furthermore, no user has complained about it not working.
However, I have recently bought a Galaxy S3, and it does not work as expected. When I set the alarm (using the told preferences) a few minutes in the future, it works as expected: the BroadcastReceiver is awaken, the wifi is turned on, the waiting is waited, the job is done and the wifi is turned off.
But if I set the alarm in the night (for example, 3:00:00) it does not: the alarm is triggered, the wifi is turned on... and nothing else. Neither the job is done nor obviously the wifi is not turned off at the end. I have created logs and postDelayed() is invoked, but the Runnable.run() is never called.
It seems that my BroadcastReceiver process is dying before run() is called.
Any idea why? Any idea about how can I avoid it?

A:

BroadcastReceivers are always destroyed immediately after use.  I'm not sure if it changed in some previous version of Android, but you should never assume that an instance of a broadcast receiver will stay around.  Their purpose is immediate processing of an event, delayed processing like that should happen using AlarmManager or in a service.

