This article teaches how to use handler and Runnable in Android.Before that we would see what is a handler and runnable in android.
What is Handler ...?A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
Uses of Handler...?
There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future;
(2) to enqueue an action to be performed on a different thread than your own.
What is Runnable ...?
Runnable is just an interface you need to instantiate a thread to contain it. Whereas thread already contains the ability to spawn a thread.If you extend Thread you can't extend anything else (Java doesn't support multiple inheritance). You can have multiple interfaces on a class, therefore you could have Runnable.
The main use of Runnable is run code in a different Thread.
Example :
This Example Displaying Toast with the use of Handler and Runnable Simultaneously.
package com.example.simple_handler_example;
import android.app.Activity;handler.postDelayed(runnable, 10000);//Run Simultaneously each 10000 milliseconds
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Runnable Starts
runnable = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"HAI",Toast.LENGTH_LONG).show();
}
};
handler = new Handler();
handler.postDelayed(runnable, 1000);//Starts After 1000 milliseconds
}
@Override
protected void onStop() {
super.onStop();
// To stop the handler
handler.removeCallbacks(runnable);
}
Output
}
Screen Shot :

No comments:
Post a Comment