Handler in Android. Handler PostDelayed() method & Post() in Android.

The Handler runs on the Main thread.

It doesnt create a seperate thread and run  on worker thread.

The Handler has 2 main methods- Postdelayed() and Post()

---------------------------------------------------------------------------------------------------------------------------
1] Handler.PostDelayed()

This method is used when we want to run a code on the Main/UI thread after a certain amount of time.

if you use this method , you have to provide a Time after whiihc the code gets executed.


Step 1] Create a Handler Object and Implement the Postdelayed() method on it.


public class MainActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = findViewById(R.id.Button1);
button.setOnClickListener(listener);
}

View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {

TextView textView = findViewById(R.id.textview1);
textView.setText("Hello World !");

}
},5000);
}
};

}



step 2] The Postdelayed() method takes two agruments , A runnable object and the Time after whihc the code must be executed.


--------------------------------------------------------------------------------------------------------------------------

2] Handler.Post() 

This method takes only one Argument i.e a Runnable object.

This method adds the Code into the WorkQue and executes it immitiately on its Turn.



-----------------------------------------------------------------------------------



Useful video which explains both the Methods :

https://youtu.be/BVkT-lrDgm0




















Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)