Monday, August 12, 2013

Better to add some delay before starting service from BootReceiver

Many Android apps need to restart its services when the phone just rebooted. For example, the following code from "Learning Android" -- P162:

public class BootReceiver extends BroadcastReceiver { //
@Override
public void onReceive(Context context, Intent intent) { //
context.startService(new Intent(context, UpdaterService.class)); (1)//
Log.d("BootReceiver", "onReceived");
}
}

While, I suggestion to delay several seconds, e.g., 10 seconds, before running the (1) line, which is more stable for different phones and services.

For example, in my case, my service is going to write sd card. If you start your service immediately, some phones may fail because the sd card is not ready. 

(my app works well on Galaxy Nexus but fails on Droid. The error is java.io.filenotfoundexception: permission denied.) 

To add several-second-delay, you can do like this:

Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //run your service
            }
        }, 10000);