Skip to content Skip to sidebar Skip to footer

Schedule Task In Android

I am using below code for scheduling a task in android but its not giving any results. Please advise on the same. int delay = 5000; // delay for 5 sec. int period = 1000; // repeat

Solution 1:

TimerTasks are not ideal to use in an android environment because they're not context-aware. If your context goes away, the TimerTask will still wait patiently in the background, eventually firing and potentially crashing your app because its activity was previously finished. Or, it may keep references to your activity around after it's been closed, preventing it from being garbage collected and potentially making your app run out of memory.

Instead, use postDelayed(), which will automatically cancel the task when the activity is shut down.

finalintdelay=5000;
finalintperiod=1000;
finalRunnabler=newRunnable() {
    publicvoidrun() {
        Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
        postDelayed(this, period);
    }
};

postDelayed(r, delay);

By the way, if you ever need to cancel your task manually, you can use removeCallbacks(r) where r is the runnable you posted previously.

Solution 2:

I got the answer as per below code:

publicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Timertimer=newTimer();

    timer.schedule(newScheduledTaskWithHandeler(), 5000);

}

finalHandlerhandler=newHandler() {

   publicvoidhandleMessage(Message msg) {
       Toast.makeText(getApplicationContext(), "Run!",
           Toast.LENGTH_SHORT).show();
   }
};

classScheduledTaskWithHandelerextendsTimerTask {

    @Overridepublicvoidrun() {
        handler.sendEmptyMessage(0);
    }
}

Post a Comment for "Schedule Task In Android"