Android Application Development BASICS (5) -- handler and Multithreading

Source: Internet
Author: User

I. Overview

Handler is mainly used to send and process messages. It has multiple message sending functions, but only one handlemessage () function is used to process messages ().


Ii. Requirements

There are two threads in the program. One is the UI thread and the other is the self-created thread. messages are sent in the self-created thread and received and processed in the UI thread.

 

Iii. Implementation

Not only Android, but many other interface programming methods do not allow you to directly update the UI in other threads. Therefore, you can send some messages to the UI thread in other threads to update the interface.

Create a project myhandler and modify/RES/layout/main. in the XML layout file, add two button buttons, one empty view (mainly for typographical use) and one text textview. The complete main. xml file is as follows:

1 <? XML version = "1.0" encoding = "UTF-8"?>
2 <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
3 Android: layout_width = "fill_parent"
4 Android: layout_height = "fill_parent"
5 Android: Orientation = "vertical">
6
7 <button
8 Android: Id = "@ + ID/mbutton"
9 Android: layout_width = "fill_parent"
10 Android: layout_height = "wrap_content"
11 Android: text = "Startup thread"
12 Android: textsize = "15px"
13/>
14
15 <button
16 Android: Id = "@ + ID/sbutton"
17 Android: layout_width = "fill_parent"
18 Android: layout_height = "wrap_content"
19 Android: text = "stop a thread"
20 Android: textsize = "15px"
21/>
22
23 <View
24 Android: layout_width = "fill_parent"
25 Android: layout_height = "70px"
26/>
27
28 <textview
29 Android: Id = "@ + ID/mtextview"
30 Android: layout_width = "fill_parent"
31 Android: layout_height = "wrap_content"
32 Android: text = ""
33 Android: textcolor = "# ff0000"
34 Android: textsize = "50px"
35 Android: gravity = "center_horizontal"
36/>
37
38 </linearlayout>

Next, modify the myhandleractivity. Java file. This file defines two classes, one of which is the mhandler class. It inherits from the handler class and implements the handlemessage (Message MSG) function. The other is the mthread class, which inherits from the Thread class and implements the run () function. Other detailed annotations are provided in the program. The complete myhandleractivity. Java file is as follows:

1 package com. Nan. Handler;
2
3 Import Android. App. activity;
4 Import Android. OS. Bundle;
5 import Android. OS. Handler;
6 Import Android. OS. message;
7 Import Android. View. view;
8 Import Android. widget. Button;
9 Import Android. widget. textview;
10
11 public class myhandleractivity extends Activity
12 {
13 // indicates whether the thread stops the flag
14 private Boolean stop = true;
15 // The thread has been started for several seconds
16 private int second = 0;
17
18 private mhandler handler;
19 private mthread thread;
20 private button mbutton;
21 private button sbutton;
22 private textview mtextview;
23
24/** called when the activity is first created .*/
25 @ override
26 Public void oncreate (bundle savedinstancestate)
27 {
28 super. oncreate (savedinstancestate );
29 setcontentview (R. layout. Main );
30
31 handler = new mhandler ();
32 thread = new mthread ();
33
34 mtextview = (textview) findviewbyid (R. Id. mtextview );
35 mbutton = (button) findviewbyid (R. Id. mbutton );
36 // set the "start thread" button to handle the event
37 mbutton. setonclicklistener (New View. onclicklistener ()
38 {
39
40 @ override
41 public void onclick (view V)
42 {
43 // todo auto-generated method stub
44 // set the flag
45 stop = false;
46 // start a new thread
47 thread. Start ();
48
49}
50 });
51 sbutton = (button) findviewbyid (R. Id. sbutton );
52 // set the "Stop thread" button for event handling
53 sbutton. setonclicklistener (New View. onclicklistener ()
54 {
55
56 @ override
57 public void onclick (view V)
58 {
59 // todo auto-generated method stub
60 // set the flag
61 stop = true;
62}
63 });
64
65}
66
67 // Custom Handler class
68 private class mhandler extends Handler
69 {
70 @ override
71 public void handlemessage (Message MSG)
72 {
73 switch (msg. What)
74 {
75 Case 1:
76 {
77 // increase in the number of seconds
78 second ++;
79 // displayed in seconds
80 mtextview. settext (integer. tostring (second ));
81 break;
82}
83}
84}
85}
86
87 // custom Thread class
88 private class mthread extends thread
89 {
90
91 @ override
92 // execute this function when the thread starts
93 public void run ()
94 {
95 // keep repeating until the flag bit is "true"
96 while (! Stop)
97 {
98 try {
99 // 1 second delay
100 thread. Sleep (1000 );
101} catch (interruptedexception e ){
102 // todo auto-generated Catch Block
103 e. printstacktrace ();
104}
105 message MSG = new message ();
106 // message flag
107 MSG. What = 1;
108 // send this message
109 handler. sendmessage (MSG );
110}
111}
112}
113
114}

Okay. Run the program.

Click the "enable thread" button as follows:

Click the "Stop thread" button and find that the count is stopped, indicating that the newly opened thread has exited.

Complete.

 

 

 

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.