tags:

views:

65

answers:

2

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 every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

   public void run() {
      Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
   }

}, delay, period);
A: 

I got the answer as per below code:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   Timer timer = new Timer();

   timer.schedule(new ScheduledTaskWithHandeler(), 5000);

}

final Handler handler = new Handler() {

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

class ScheduledTaskWithHandeler extends TimerTask {

@Override
public void run() {
   handler.sendEmptyMessage(0);
}
Maneesh
A: 

Why use a handler and send a message? Why doesn't an ordinary void method call work?

I am sure the handler is correct to use, but why??? Your reply may help me to understand why I get so many forced stops for no apparent (to me) reason?

Droid
Look Timer class run a normal java thread in background and this thread never executed on UI so whenever this thread completes the task it dens a message to handle which is act likes communication between thread and currently executing code. That's it. Hope u got the point. Actual answer is posted as answer.
Maneesh