1.

Implement an AsyncTask that repeats itself after a given interval?

Answer»

For creating AsyncTask with a specific interval, we can USE a Handler. A Handler is a safe option because we don't need an extra THREAD to keep tracking when firing the event.

When we LAUNCH any android application it will create a thread which called the Main thread, this thread is handling all the UI event handling so it is also called as UI Thread. A Handler is also a Thread which is running on Main Thread. A Handler allows you to send and PROCESS Message and Runnable objects associated with a thread's MessageQueue. A Handler can be used to schedule messages or runnable to executed at some point in the future. You can send a message using Handler

// Create the Handler object (on the main thread by default) Handler handler = new Handler(); // Define the code block to be executed private Runnable runnableCode = new Runnable() {    @Override    public void run() {      // Do SOMETHING here on the main thread      Log.d("Handlers", "Called on main thread");    } }; // Run the above code block on the main thread after 2 seconds handler.postDelayed(runnableCode, 2000);


Discussion

No Comment Found

Related InterviewSolutions