Android neutron thread and UI thread communication _android

Source: Internet
Author: User
Tags thread class

Detailed explanation of communication between the Android neutron thread and the UI thread

1. In multithreaded programming this piece, we often have to use handler,thread and runnable these three classes, then the relationship between them do you understand it?
2. First of all, the principles of single-threaded models must be followed in developing Android applications:
Android UI actions are not thread-safe and must be performed in the UI thread.
3.Handler:
(1). Concept:
Handler is the bridge between activity and thread/runnable. Handler, which runs in the main UI thread, can pass data through a message object with a child thread.
(2). Use:
The A:handler is run in the UI thread, sending data information primarily to the child thread and using this data to update the UI with the main thread to interact with the UI main thread. For example, you can send a message with handler and then receive and process it in a handler thread.
B: The processor of the message. By handler the object we can encapsulate the message object and then add the message object to the MessageQueue via SendMessage (msg), and when MessageQueue loops to the message, The Handlemessage () method of the handler object corresponding to the message object is invoked to process it.
C:handler can distribute Runnable objects, or you can distribute message objects.

4.Message:
A Message object, as its name implies, is a class that records message information. In other words, it is the carrier of information, storing information content. There are several more important fields for this class:

(1). Arg1 and Arg2: We can use two fields to store the integer value we need to pass, and in the service we can store the service ID.
(2). obj: The field is type object, and we can have the field pass an object to the recipient of the message.
(3). What: This field can be said to be the flag of the message, to determine which message is received. In message processing, we can do different things depending on the value of the field, similar to what button we clicked when we handled the button event by switch (V.getid ()).
Android recommends getting the message object via Message.obtain () or handler.obtainmessage (). This is not necessarily a direct creation of a new instance, but rather the presence of a message instance that is available from the pool of messages, which is directly fetched and returned. Conversely, if there is no message instance available in the messages pool, a new one is given based on the parameter. By analyzing the source, the Android system instantiates 10 message objects in the messaging pool by default.
5. SOURCE Display:
(1). activity_main.xml layout file:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:id=" @+id/container "android:layout_width=" Match_parent "android:layout_height=" "Match_parent" android:orientation= "vertical" > <button android:id= "@+id/btn android:layout_width=" Wra P_content "android:layout_height=" wrap_content "android:text=" Custom thread inheritance thread/> <button android: Id= "@+id/btn2" android:layout_width= wrap_content "android:layout_height=" wrap_content "android:text=" Custom Runna ble implement runnable "/> <button android:id=" @+id/btn3 "android:layout_width=" "Wrap_content" Android:layout_
    height= "Wrap_content" android:text= "Regular update UI interface, handler distribution runnable object"/> <button android:id= "@+id/btn4" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "regularly updates the UI interface,
 Handler distribution Message Object "/> <textview android:id=" @+id/tv "   Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "0"/> </LinearLay

 Out>

(2). Mainactivity.java

Package Com.chengdong.su.threaddemo;
Import com.chengdong.su.threaddemo.util.MyRunnable;

Import Com.chengdong.su.threaddemo.util.MyThread; Import Android.
R.integer;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

Import Android.widget.TextView; public class Mainactivity extends activity implements Onclicklistener {/** tag/private final String tag = GetClass
  (). Getsimplename ();
  /** the object of the button/private button Mbutton;
  /** the object of the button/private button mButton2;
  /** the object of the button/private button mButton3;
  /** the object of the button/private button mButton4;
  /** the object of the TextView * * Private TextView Mtextview;
  /** count */private int mcount = 0;

  /** sign */private int message_flag = 1; How/** * Handler Distribute runnable objects
   * Private Handler Mhandler = new Handler ();
      Runnable Runnable = new Runnable () {@Override public void run () {mcount++;
      Mhandler.postdelayed (runnable, 1000);

    Mtextview.settext (Mcount + "");
  }
  }; /*** * Handler the way to distribute the message object * * Handler mHandler2 = new Handler () {public void Handlemessage (android.os.Mess
      Age msg) {if (Msg.what = 1) {mtextview.settext ("How handler distributes the Message object");

  }
    }
  };
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);

  Initview ();
    /** * Initialize Component object/private void Initview () {Mbutton = (Button) Findviewbyid (R.ID.BTN);
    MButton2 = (Button) Findviewbyid (R.ID.BTN2);
    MButton3 = (Button) Findviewbyid (R.ID.BTN3);

    MButton4 = (Button) Findviewbyid (R.ID.BTN4);
    Mbutton.setonclicklistener (this);
    Mbutton2.setonclicklistener (this); Mbutton3.setonclicklistEner (this);

    Mbutton4.setonclicklistener (this);

  Mtextview = (TextView) Findviewbyid (r.id.tv); @Override public void OnClick (View v) {switch (V.getid ()) {case R.ID.BTN: {//Method One: Inherited way: Custom Thread Relay
      Bearing thread, open a new Thread (Mythread). Start ();
    Break
      Case R.ID.BTN2: {//Method two: How to implement: Implement Runnable new Thread (New Myrunnable ()). Start ();
    Break //Method Three: Handler distribution runnable object: Scheduled update UI interface submit scheduled task immediately execute case R.ID.BTN3: {//handler distribute Runnable object Mhandler.po
      St (runnable);
    Break //Method IV: Handler distribution Message object, scheduled update UI interface submit scheduled task immediately execute case R.ID.BTN4: {///not recommended this way//message msg = new Me
      Ssage ();
      This is the recommended way to get objects: Get the Message object available from the pool of messages msg = Message.obtain ();
      Msg.what = Message_flag;
      Mhandler2.sendmessage (msg);
    Break
    } Default:break;

 }

  }
}

(3). Myrunnable.java

Package com.chengdong.su.threaddemo.util;

Import Android.util.Log;

/***
 * Custom a myrunnable thread
 * 
 * * @author SCD
 */public
class Myrunnable implements Runnable { Public

  myrunnable () {
    super ();
  }

  /** Tag */
  private final String tag = GetClass (). Getsimplename ();

  @Override public
  Void Run () {(
    int i = 0; i < i++) {
      log.e (TAG, Thread.CurrentThread (). GetName () + ", implemented method" + i);

    }}

  }



(4) Mythread.java

Package com.chengdong.su.threaddemo.util;

Import Android.util.Log;

/***
 * Customize a thread
 * 
 * @author SCD * * 
 /Public
class Mythread extends thread {public

  mythread ( ) {
    super ();
  }

  /** Tag */
  private final String tag = GetClass (). Getsimplename ();

  @Override public
  Void Run () {
    super.run ();
    for (int i = 0; i < i++) {LOG.E (
      TAG, Thread.CurrentThread (). GetName () + ", Inheriting Thread class:" + i);

    }
  }

}

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.