Why use a handler?

I came across this code in a very basic Handler tutorial. The code works fine, but I don’t understand why I should use Handler for progressDialog.dismiss() ??? I removed the part of the handler and put progressDialog.dismiss() in the run() method and it worked fine. So why use a handler ???

  import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class HandlerThread extends Activity{ private Button start; private ProgressDialog progressDialog; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); start = (Button) findViewById(R.id.Button01); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub fetchData(); } }); } protected void fetchData() { // TODO Auto-generated method stub progressDialog = ProgressDialog.show(this, "", "Doing..."); new Thread() { public void run() { try { Thread.sleep(8000); } catch (InterruptedException e) { } messageHandler.sendEmptyMessage(0); } }.start(); } private Handler messageHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); progressDialog.dismiss(); } }; } 
+7
source share
4 answers

From the View documentation :

You should always be in the user interface thread when calling any method on any View. If you are working on other threads and want to update the view state from that thread, you should use the Handler .

In your example, when you have to call the dismiss() method on the ProgressDialog as above, you have to do it from the user interface thread. messageHandler initialized by an instance of a Handler when an instance of the HandlerThread class (presumably in the user interface thread).

From the Handler documentation :

Each Handler instance is associated with one thread and that thread's message queue. When you create a new Handler , it needs a thread / message queue for the thread that creates it - from now on, it will deliver messages and runnables to this queue message and execute them when they exit the message queue.

So, to connect to the user interface thread from your new thread, just send a message to the Handler created in the user interface thread.

If you invoke methods on the View because of the UI thread, it invokes undefined behavior, which means that it can work just fine. But it is not always guaranteed to work fine.

+17
source

Why use Handler in Android?


First: let us know what a stream is:

  • Multitasking topics help
  • Themes can be taught as a mini-process running in the main process.
  • Streams allow at least parallel execution of an appearance

Second: tell us about the application:

  • When the Android application is launched, the runtime will create one main thread, this main thread will take care of the execution of all components in android

Android UI-Toolkit is not thread safe

  • As was said, there are many components in the main Android thread, now suppose that one of the components takes a long time to execute, then this makes the main thread inactive and it will show the application is not responding
  • Subflows cannot directly manipulate the application (main) thread in android
  • The handler acts as an interface and collects messages from sub-threads and update the main thread of the application one by one as a message, the thread handlers are implemented in the main thread.

Handler Class:

  • For multithreading, we will use a handler class that comes from the android.os.Handler package
  • Each thread is processed by one instance of the handler class.

Figure

  • As you can see from the above figure, each thread is processed by one instance of the Handler class.
  • threads interact with each other using messages
  • This handler class helps maintain some synchronization of b / w streams, allowing them to work together to achieve multithreading.

Handler instance is running

 Handler handlerObject = new Handler(); 

The final part of using a handler is to use the Runnable Interface:

  • the handler class uses the runnable interface to implement multithreading
  • We override the run method to execute the thread a certain amount of time.

 Class NameOfClass implements Runnable { Public void run() { //Body of run method } } 

Unification of all

 //Create handler in the thread it should be associated with //in this case the UI thread final Handler handler = new Handler(); Runnable runnable = new Runnable() { public void run() { while(running){ //Do time consuming stuff //The handler schedules the new runnable on the UI thread handler.post(new Runnable() { //Ex.. using progressbar to set the pogress //Updating the UI is done inside the Handler }); } } }; new Thread(runnable).start(); 
+29
source

The simpler the better. Instead of using a handler, you can try using the following code:

 runOnUiThread( new Runnable() { public void run() { //Update user interface here } } ); 

Do not complicate your life;)

+4
source

when the application starts, the Android system starts the process with the main thread, which is responsible for processing the visualization of the user interface and events. The Android user interface is not thread safe, so we can only access the Android user interface through the flow of events. In your program, you defined a thread other than an event with the following code block:

  new Thread() { public void run() { try { Thread.sleep(8000); } catch (InterruptedException e) { } messageHandler.sendEmptyMessage(0); } }.start(); 

Now, if you want to reject the progress dialog, you can only do this in the event stream. A handler is used to process / process message queue messages. The handler associates with the stream, in your case, in the event stream, because by default it associates the stream in which it is created. by messageHandler.sendEmptyMessage () another thread sends a message to the handler and the handler to process this message in the handleMessage method.

+2
source

All Articles