Krishan Madushanka
Krishan Madushanka

Reputation: 389

Timer inside a service doesn't work properly on device restart

I am starting an android service and an activity after device restart using a broadcast receiver.Inside service I use a timer as follows. But after starting service the timer doesn't work properly. Timer triggers continuously without any time interval. I used the following log inside timer and it prints continuously without any time interval.

D/timer test: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

After about 1 minute timer again works properly.(with relevant time interval) I want to work the timer properly and how can I fix this?

Broadcast Receiver

public class BootReceiver extends BroadcastReceiver {

    private Intent ServiceIntent;

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

        ServiceIntent = new Intent(context, MyService.class);
        context.startService(ServiceIntent);


        Toast.makeText(context, "Boot Receiver", Toast.LENGTH_LONG).show();
        Intent intentx = new Intent(context, MainActivity.class);
        intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intentx);

    }

}

Service

public class MyService extends Service {
    private Timer timer;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("timer test", "*********************" + " Service Started " + "*********************");

        if (null != timer) {

            timer.cancel();
            timer.purge();
            timer = null;
        }

        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                Log.d("timer test", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            }
        }, 5 * 1000, 10 * 1000);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != timer) {

            timer.cancel();
            timer.purge();
            timer = null;
        }
    }
}

Upvotes: 0

Views: 123

Answers (0)

Related Questions