5

hi When my app get the ACTION_BOOT_COMPLETED it starts a service. I would like to delay that for lets say 60sec. Can i do that in the:

public class StartAtBootServiceReceiver extends BroadcastReceiver 
{

        public void onReceive(Context context, Intent intent) 
        {
           // Delay...60sec
        }
}
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
Erik
  • 5,039
  • 10
  • 63
  • 119

2 Answers2

4

use Timer() and TimerTask():

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //run your service
            }
        }, 60000);
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • thanks will try that, also Prashast is talking about AlarmManager. What is best? – Erik Dec 30 '10 at 16:24
  • for such a simple delay AlarmManager is an overhead. It is used in more complicated cases. – Vladimir Ivanov Dec 30 '10 at 16:47
  • Android docs state "there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed". Hence, using Timer in onReceive might be unreliable. I would go with AlarmManager! – wrygiel May 28 '12 at 08:17
  • 1
    For clarification - of course, the scheduling is instant and onReceive ends quickly, but the Receiver object has to remain in memory for the TimerTask to work. But since after leaving onReceive the receiver object MAY be freed by system, you should not use it. – wrygiel May 28 '12 at 08:25
2

When you receive the BOOT_COMPLETED intent you should use the AlarmManager to setup an pending intent that will fire after 60 seconds.

Prashast
  • 5,645
  • 3
  • 30
  • 31