Multi-thread programming in Android (1) with source code and android multi-thread programming

Source: Internet
Author: User

Multi-thread programming in Android (1) with source code and android multi-thread programming

Multi-Thread programming in Android: Conceptual Analysis of Handler, Runnable, and Thread classes

1. Handler class:

Handler is a mechanism encapsulated by Google: it can be used to update the UI and send and process messages. Handler is run in the main thread (UI thread ).

(2) reasons for using the Handler mechanism:

This is a UI update mechanism and message mechanism encapsulated by Google. If this mechanism is not used to update the UI and send and process messages, an exception is thrown.

(3) Handler usage:

Handler actually sends messages to himself. That is to say, you can send and process it yourself. It is because the Handler is internally associated with the logoff.
A. Update the UI:

Package com. chengdong. su. handlerdemo; import android. app. activity; import android. app. actionBar; import android. app. fragment; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. view. layoutInflater; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. OS. build;/*** Handler Purpose 1: update the component ** @ author scd **/public class MainActivity extends Activity {private ImageView mView; /** data source */private int [] mImage = {R. drawable. ic_1, R. drawable. ic_2, R. drawable. ic_3};/** location of the image */private int mIndex = 0;/** the object of the Handler */private Handler mHandler = new Handler (); /** the object of the Runnable */private MyRunnable mRunnable = new MyRunnable (); Runnable runnable = new Runnable () {@ Override public void run () {mIndex ++; mIndex = mIndex % 3; mView. setImageResource (mImage [mIndex]); // call the Runnable object again and call the run () method mHandler every second. postDelayed (runnable, 1000) ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. fragment_main); init (); // Method 1: // mHandler. postDelayed (runnable, 1000); // Method 2: Customize the Runnable object mHandler. postDelayed (mRunnable, 1000);}/***** init the view */private void init () {mView = (ImageView) findViewById (R. id. imageView1);}/*** task: 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 and call the run () method mHandler every second. postDelayed (mRunnable, 1000 );}}}

B. Message Processing:

Package com. chengdong. su. handlerdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. util. log; import android. widget. imageView;/*** Handler Purpose 1: update the component ** @ author scd **/public class MainActivity extends Activity {private String TAG = "MainActivity "; private boolean Flag; private ImageView mView;/** the object of the Handler */private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case 0: {mView. setImageResource (R. drawable. ic_1); Log. d (TAG, "Message 1"); break;} case 1: {mView. setImageResource (R. drawable. ic_2); Log. d (TAG, "Message 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 runs in the UI thread and does not create a new thread. The Runnable class is an interface that overwrites the run () method in the class to implement business logic requirements. To update the components in the UI. The Runnable class is just a task interface. Is the task executed by the enabled thread.

3. Thread class:

Implement the run () method in the Runnable class. The Thread class calls the run () method to run the newly opened Thread. The content to be executed by the Thread is completed in the run () method.

(1). start () method:This method starts a thread. However, this thread is in the ready state and is not running. Then, the Thread system class automatically calls the run () method to complete the operation.

(2). run () method:This method becomes the thread body. Contains the content of the thread to be executed. The run () method ends and the thread ends.

Package com. chengdong. su. handlerdemo; import android. app. activity; import android. app. actionBar; import android. app. fragment; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. util. log; import android. view. layoutInflater; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. widget. textView; import android. widget. toast; import android. OS. build;/***** @ author scd **/public class SecondActivity extends Activity {private String TAG = getClass (). getSimpleName (); private TextView mView; private MyThread mThread; private Handler mHandler = new Handler () {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 1: new Thread () {public void run () {System. out. println ("---> New Thread:" + Thread. currentThread (). getId ());};}. start (); // Method 2: new Thread (new Runnable () {@ Override public void run () {System. out. println ("---> New Thread:" + Thread. currentThread (). getId ());}}). start ();} private void init () {mView = (TextView) findViewById (R. id. textView1);} class MyThread extends Thread {public Handler mHandler2; @ Override public void run () {// create a message carrier object logoff. prepare (); mHandler2 = new Handler () {public void handleMessage (android. OS. message msg) {Toast. makeText (getApplicationContext (), "111", 1 ). show () ;};}; // Loop Mechanism logoff. loop ();}}}

Summary:
Runnable () is just an abstract task, not a multi-thread. Thread. start () is a new multi-Thread. In addition, the Thread is executed in the new Thread and the run () method is executed. Multithreading is a Thread implementation, which has little to do with Runnable. The thread is used to make better use of the CPU and increase the program running rate!

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.