Android Timer and TimerTask scheduling

12:58 AM Nilesh Deokar 0 Comments

All you need to do is write a function which will schedule the timerTask and call it in the onCreate().
then manage the activity life cycle with the timer task.

public void callAsynchronousTask() {

        final Handler handler = new Handler();
        timer = new Timer();
        doAsynchronousTask = new TimerTask() {
            @Override            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {


                            TaskFinder tf = new TaskFinder(MainActivity.this);
                            tf.execute();
                            isTimerRunning=true;

                        } catch (Exception e) {
                            // TODO Auto-generated catch block                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 30000); //execute in every 30 sec    }
Call this function from the onCreate()

protected void onCreate(Bundle savedInstanceState) {
    // requestWindowFeature(Window.FEATURE_ACTION_BAR);    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    ...
    callAsynchronousTask();
}
here is how you manage the onStop() and onRestart() of the activity.

@Overrideprotected void onStop() {
    //thread stop here
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
    super.onStop();

}

@Overrideprotected void onRestart() {
    callAsynchronousTask();
    super.onRestart();

}

0 comments: