Multi-threaded programming in Android (i) attached source code

Source: Internet
Author: User

Multithreaded programming in Android: Conceptual analysis of Handler class, Runnable class, Thread class

1.Handler class:

Handler is a mechanism for Google encapsulation: the ability to update the UI and send and process messages. Handler is performed on the main thread (UI thread).

(2). Reasons for using the handler mechanism:

This is a Google package update UI mechanism and message mechanism. The exception is thrown if you do not use this to update the UI and send processing messages.

(3). Use of handler:

handler sends a message to itself in fact. This means that it is sent and processed by itself. is due to handler internal and looper associated.
A. Updating the UI interface:

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.app.ActionBar;ImportAndroid.app.Fragment;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.view.LayoutInflater;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ImageView;ImportAndroid.os.Build;/** * Handler use 1: Update the components in the UI interface * * @author SCD * */ Public  class mainactivity extends Activity {    PrivateImageView MView;/** Data Source * /    Private int[] Mimage = {r.drawable.ic_1, r.drawable.ic_2, r.drawable.ic_3};/** where the picture is located * /    Private intMindex =0;/** The object of the Handler * *    PrivateHandler Mhandler =NewHandler ();/** The object of the Runnable * *    PrivateMyrunnable mrunnable =NewMyrunnable (); Runnable Runnable =NewRunnable () {@Override         Public void Run() {mindex++; Mindex = mindex%3; Mview.setimageresource (Mimage[mindex]);//Call the Runnable object again, call the run () method every secondMhandler.postdelayed (runnable, +); }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.fragment_main); Init ();//Method One:        //Mhandler.postdelayed (runnable, +);        //Method Two: Define your own Runnable objectMhandler.postdelayed (Mrunnable, +); }/*** * Init the view * *    Private void Init() {MView = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); }/** * Mission: Business logic * * @author SCD * */    Private  class myrunnable implements Runnable {        @Override         Public void Run() {mindex++; Mindex = mindex%3; Mview.setimageresource (Mimage[mindex]);//Call the Runnable object again, call the run () method every secondMhandler.postdelayed (Mrunnable, +); }    }}

B. Message Processing:

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.util.Log;ImportAndroid.widget.ImageView;/** * Handler use 1: Update the components in the UI interface * * @author SCD * */ Public  class mainactivity extends Activity {    PrivateString TAG ="Mainactivity";Private BooleanFlag;PrivateImageView MView;/** The object of the Handler * *    PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Android.os.Message msg) {Switch(msg.what) { Case 0: {Mview.setimageresource (r.drawable.ic_1); LOG.D (TAG,"MSG 1"); Break; } Case 1: {Mview.setimageresource (r.drawable.ic_2); LOG.D (TAG,"MSG 2"); Break; }default: Break;    }        }; };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.fragment_main); Init ();if(Flag) {Mhandler.sendemptymessage (0); }Else{Mhandler.sendemptymessage (1); }    }/*** * Init the view * *    Private void Init() {MView = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); }}

2.Runnable class:

The Runnable class is executed in the UI thread and does not create a new thread. The Runnable class is an interface that implements the business logic requirements by covering the run () method in the class.

To update the components in the UI interface. The Runnable class is just a task interface. is an open thread that performs the task.

3.Thread class:

Implementing the Run () method in the Runnable class, the thread class calls the run () method to execute the newly opened thread, and the content that the thread needs to execute is completed in the run () method.

(1). Start () Method: The method starts a thread.

However, this thread is in a ready state and is not executed. The thread system class then invokes the run () method on its own initiative to complete the operation.

(2). Run () Method: The method becomes the thread body. Includes the contents of the thread to be executed. The run () method execution ends and this thread terminates.

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.app.ActionBar;ImportAndroid.app.Fragment;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.util.Log;ImportAndroid.view.LayoutInflater;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;ImportAndroid.os.Build;/** * * @author SCD * */ Public  class secondactivity extends Activity {    PrivateString TAG = GetClass (). Getsimplename ();PrivateTextView MView;PrivateMyThread Mthread;PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Android.os.Message msg) {LOG.D (TAG,"Thread UI:"+ Thread.CurrentThread (). GetId ()); Mview.settext ("111");    }; };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Init (); System.out.println ("--->ui thread:"+ Thread.CurrentThread (). GetId ());//Method One:        NewThread () { Public void Run() {System.out. println ("---> New threads:"+ Thread.CurrentThread (). GetId ());        }; }.start ();//Method two:        NewThread (NewRunnable () {@Override             Public void Run() {System.out. println ("---> New threads:"+ Thread.CurrentThread (). GetId ());    }}). Start (); }Private void Init() {MView = (TextView) Findviewbyid (R.ID.TEXTVIEW1); } class MyThread extends Thread { PublicHandler MHandler2;@Override         Public void Run() {//Create a message carrier objectLooper.prepare (); MHandler2 =NewHandler () { Public void Handlemessage(Android.os.Message msg) {Toast.maketext (Getapplicationcontext (),"111",1). Show ();            }; };//Cycle mechanismLooper.loop (); }    }}

Summary:
Runnable () is just an abstraction of a task, not multithreading. Thread.Start () is a new multi-threaded. and threads are executed on the newly-opened thread. Executes the run () method. Multithreading is the thread implementation, and runnable is not much of a relationship. Threads are designed to better utilize the CPU and increase the rate of program execution.

Multi-threaded programming in Android (i) attached source code

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.