Android asynchronously updates the UI ---- handler + thread

Source: Internet
Author: User

Android applications are in single-threaded mode. The single-thread mode requires two things to be remembered: 1. Prevent UI thread blocking 2. Ensure that the Android UI toolkit is accessed only in the UI thread. The single-thread model principle must be observed when developing Android applications: android UI operations are not thread-safe and must be executed in the UI thread. Every Android application runs in a dalvik virtual machine process. When a process starts, a main thread (MainThread) is started. The main thread is responsible for processing ui-related events, therefore, the main thread is often called the UI thread. Because Android uses a single-threaded UI model, you can only operate the UI elements in the main thread. Open a Thread or execute time-consuming operations in the background Thread. For example, public void onClick (View v) {new Thread (new Runnable () {public void run () {Bitmap B = loadImageFromNetwork (); // download the mImageView image from the network. setImageBitmap (B); // set the image to ImageView }}). the code above start ()} will report an error. You may say that the logic is correct, but it violates the Android single-thread model: android UI operations are not thread-safe and must be executed in the UI thread. for example, if you operate the UI directly in a non-UI thread, the following error occurs: CalledFromWrongThreadException: only the original thread that created. View hierarchy can touch its views Android provides a mechanism for our information loop. We can use this mechanism to implement inter-thread communication. Then, we can send messages to the UI thread in a non-UI thread, and finally let the Ui thread perform ui operations. Andriod provides several methods to access the UI thread in other threads: Activity. runOnUiThread (Runnable) View. post (Runnable) View. postDelayed (Runnable, long) Hanlder requires a new thread to deal with the heavy workload of operations and IO operations, so as not to block the ui thread. Example: The following example shows how to use Thread + Handler to send a message to a non-UI Thread to notify the UI Thread to update ThradHandlerActivity. java: [java] <span style = "font-size: 18px"> package com. example. thread; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import com. example. test. r; import android. annotation. suppress Lint; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; 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. imageView; import android. widget. toast; public class ThreadHandlerActivity extends Activity {p Rivate static final int MSG_SUCCESS = 0; private static final int MSG_FAILURE = 1; private ImageView mImageView; private Button mButton; private Thread mThread; @ SuppressLint ("HandlerLeak ") private Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case MSG_SUCCESS: mImageView. setImageBitmap (Bitmap) msg. obj); Toast. makeText (getApplication ()," Function acquisition image ", Toast. LENGTH_LONG ). show (); break; case MSG_FAILURE: Toast. makeText (getApplication (), "failed to get image", Toast. LENGTH_LONG ). show (); break;} super. handleMessage (msg) ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. thread_layout); mImageView = (ImageView) findViewById (R. id. logo); // display the image's ImageView mButton = (Button) findVie WById (R. id. click); mButton. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {if (mThread = null) {mThread = new Thread (runnable); mThread. start ();} else {Toast. makeText (getApplication (), "thread already running", Toast. LENGTH_LONG ). show () ;}}) ;}runnable Runnable = new runnable () {@ Override public void run () {HttpClient hc = new DefaultHttpClient (); HttpGet hg = new HttpG Et ("http://csdnimg.cn/www/images/csdnindex_logo.gif"); final Bitmap bm; try {HttpResponse hr = hc.exe cute (hg); bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ();} catch (Exception e) {e. printStackTrace (); mHandler. obtainMessage (MSG_FAILURE ). sendToTarget (); return;} mHandler. obtainMessage (MSG_SUCCESS, bm ). sendToTarget (); // mImageView. setImageBitmap (bm); // error! You cannot operate the ui element in a non-ui thread // mImageView. post (new Runnable () {// another more concise method for sending messages to the ui thread. /// @ Override // public void run () {// run () method will be executed in the ui thread // mImageView. setImageBitmap (bm); //}) ;};}</span> for the above method, we use handler + Thread to update the UI, [java] <span style = "font-size: 18px"> mImageView. setImageBitmap (bm); // error! You cannot operate the ui element in a non-ui thread </span>. In fact, we mentioned a method Activity. runOnUiThread (Runnable), which starts the Runnable as a UI thread [java] <span style = "font-size: 18px ">/*** Runs the specified action on the UI thread. if the current thread is the UI * thread, then the action is executed immediately. if the current thread is * not the UI thread, the action is posted to the event queue of the UI thread. ** @ param action the action to run on The UI thread */public final void runOnUiThread (Runnable action) {if (Thread. currentThread ()! = MUiThread) {mHandler. post (action) ;}else {action. run () ;}</span> the runOnUiThread (Runnable) method of the above Activity is implemented. Use Activity. runOnUiThread (Runnable) to create the updated ui code in Runnable. Then, when you need to update the ui, pass the Runnable object to Activity. runOnUiThread (Runnable ). In this way, the Runnable object can be called in the ui program. If the current thread is a UI thread, the action is immediately executed. If the current thread is not a UI thread, the operation is the UI thread published to the event queue. Example: [java] <span style = "font-size: 18px"> current_activity.this. runOnUiThread (new Runnable () @ Override public void run () {// operation code of the refresh ui}); </span> note that runOnUiThread is a method in the Activity, in the thread, we need to tell the system which activity is called. so let's modify the above Code: [java] <span style = "font-size: 18px"> package com. example. thread; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import Org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import com. example. test. r; import android. annotation. suppressLint; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onClick Listener; import android. widget. button; import android. widget. imageView; import android. widget. toast; public class ThreadHandlerActivity extends Activity {private static final int MSG_SUCCESS = 0; private static final int MSG_FAILURE = 1; private ImageView mImageView; private Button mButton; @ SuppressLint ("HandlerLeak ") private Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case MSG_SUCCESS: mImageView. setImageBitmap (Bitmap) msg. obj); Toast. makeText (getApplication (), "image retrieved successfully", Toast. LENGTH_LONG ). show (); break; case MSG_FAILURE: Toast. makeText (getApplication (), "failed to get image", Toast. LENGTH_LONG ). show (); break;} super. handleMessage (msg) ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState ); SetContentView (R. layout. thread_layout); mImageView = (ImageView) findViewById (R. id. logo); // ImageView mButton = (Button) findViewById (R. id. click); mButton. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {ThreadHandlerActivity. this. runOnUiThread (runnable) ;}}) ;}runnable Runnable = new runnable () {@ Override public void run () {HttpClient hc = new DefaultHttp Client (); HttpGet hg = new HttpGet ("http://csdnimg.cn/www/images/csdnindex_logo.gif"); final Bitmap bm; try {HttpResponse hr = hc.exe cute (hg); bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ();} catch (Exception e) {e. printStackTrace (); mHandler. obtainMessage (MSG_FAILURE ). sendToTarget (); return;} mImageView. setImageBitmap (bm) ;};}</span> can also directly update the UI in the thread. Some people will say that I pass a current Activity to a thread and then implement UI update. That is, I will call the content of the current Activity, in fact, this is also incorrect and will prompt [java] <span style = "font-size: 18px"> android. view. viewRoot $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. </span>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.