Android handler usage Summary

Source: Internet
Author: User

Method 1: (Java is used to because it does not work during Android development because it violates the single-thread model)

When I first started to use Android Thread Programming, I used to be like Java and tried to use the followingCodeSolve the problem

 
NewThread (NewRunnable (){
Public VoidRun (){
Myview. invalidate ();
}
}). Start ();

Functions can be implemented to refresh the UI. However, this does not work because it violates the single-thread model: Android UI operations are not thread-safe and must be executed in the UI thread.

Method 2: (thread + handler)

After reading the document and apidemo, I found that the commonly used method is to use handler to update the UI thread.

Handler processes UI updates based on received messages. The thread sends a handler message to notify the updated UI.

Handler myhandler =NewHandler (){
Public VoidHandlemessage (Message MSG ){
Switch(Msg. What ){
CaseTesthandler. guiupdateidentifier:
Mybounceview. invalidate ();
Break;
}
Super. Handlemessage (MSG );
}
};

 

  class  mythread  implements  runnable {
Public void Run () {
while (! Thread. currentthread (). isinterrupted () {
message = New message ();
message. what = testhandler. guiupdateidentifier;
testhandler. This . myhandler. sendmessage (Message);
try {
thread. sleep (100);
}< span style = "color: # 0000ff;"> catch (interruptedexception e) {
thread. currentthread (). interrupt ();
}< BR >}

The above method demo look: http://rayleung.javaeye.com/blog/411860

Method 3: (Java habits. In the Android platform, this cannot be done, which is related to the thread security of Android)

On the Android platform, you can use the built-in timertask class in Java for repeated periodic execution. timertask consumes less resources than thread, besides using the timer, alarmmanager provided by Android is a better solution. We need to introduce import java. util. timer; and import java. util. timertask;

Public ClassJavatimerExtendsActivity {

Timer timer =NewTimer ();
Timertask task =NewTimertask (){
Public VoidRun (){
Settitle ("Hear me? ");
}
};

Public VoidOncreate (bundle savedinstancestate ){
Super. Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

Timer. Schedule (tasks, 10000 );

}
}

 

Method 4: (timertask + handler)

Use handler to implement the timer function!

Public   Class Testtimer Extends Activity {

Timer timer = New Timer ();
Handler handler = New Handler (){
Public Void Handlemessage (Message MSG ){
Switch (Msg. What ){
Case 1:
Settitle ("Hear me? ");
Break ;
}
Super . Handlemessage (MSG );
}

};

Timertask task = New Timertask (){
Public Void Run (){
Message message = New Message ();
Message. What = 1;
Handler. sendmessage (Message );
}
};

Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

Timer. Schedule (tasks, 10000 );
}
}

 

Method 5: (runnable + handler. postdelayed (runnable, time ))

In Android, the UI is updated regularly.Java. util. Timer,Java. util. timertask, Android. OS.Handler combination. In fact, Handler itself provides the timed function.

PrivateHandler handler =NewHandler ();

PrivateRunnable myrunnable =NewRunnable (){
Public VoidRun (){

If(Run ){
Handler. postdelayed (This, 1000 );
Count ++;
}
Tvcounter. settext ("count:" + count );

}
};

Then, call

Handler. Post (myrunnable );

Handler. Post (myrunnable, time );

Case: http://shaobin0604.javaeye.com/blog/515820

========================================================== ======================================

Knowledge Point summary supplement:

Many new Android or Java developers are still confused about thread, loose, handler, and message, and derived from handlerthread and Java. util. concurrent, task, and asynctask do not discuss these issues due to books and other materials currently on the market. Today, we will make a more systematic summary of this issue. The Service, activity, and broadcast we created are all handled by a main thread. Here we can understand itUi thread. However, it takes a long time to perform some time-consuming operations, such as reading and writing large files, database operations, and network downloads. In order not to block the user interface, the ANR response Prompt window appears, at this time, we can consider using the thread to solve the problem.

ForProgramThe thread is relatively simple. You can directly create and rewrite the run method anonymously and call the start method for execution. Or inherit from the runnable interface, but for Android platform, the UI control is not designedThread security typeSo some synchronization mechanisms need to be introduced to refresh it. Google designed android to refer to the Win32 message processing mechanism.

1. Refresh A View Interface in the thread as the base class, you canUse the postinvalidate () methodIt also provides some rewriting methods, such as postinvalidate (INT left, int top, int right, int bottom), to refresh a rectangular area and perform delayed execution, for example, the postinvalidatedelayed (long delaymilliseconds) or postinvalidatedelayed (long delaymilliseconds, int left, int top, int right, int bottom) method, where the first parameter is millisecond

2. Of course, the recommended method is throughHandler to handleThese can be implemented by calling the postmessage or sendmessage method of the handler object in the run method of a thread. The Android Program maintains a Message Queue internally and will be rotated to handle these problems, if you are a Win32 programmer, you can understand the message processing well. However, compared with Android, pretranslatemessage does not provide internal interference methods.

3. What is logoff? In fact, every thread in Android is followed by a logoff. logoff can help the thread maintain a message queue, but logoff has nothing to do with handler, we can see from the open-source code that android also provides a thread inheritance class handerthread to help us deal with it. In the handlerthread object, we can get a logoff object control handle through the getlogoff method, we can map the logoff object to a handler to implement a thread synchronization mechanism. The logoff object needs to be initialized for execution. the prepare method is the problem we saw yesterday. At the same time, we need to release resources and use logoff. the release method.

4. What is message on Android? For Android, handler can pass some content. The bundle object can encapsulate string, integer, and blob binary objects.Use the sendemptymessage or sendmessage method of the handler object to pass a bundle object to the handler processor.. Provides an override method for the handler class.Handlemessage (Message MSG) is used to identify each piece of information.. Unpackage bundle to update the content in the UI thread of the handler class to refresh the control. The relevant handler object related to sendxxxx message sending methods are as follows, and there are postxxxx related methods, which are basically the same as those in Win32. One is to directly return after sending, and the other is to return after processing.

5. java. util. concurrent object analysis: programmers engaged in Java development in the past will not be unfamiliar with the concurrent object. He is an important feature added after JDK 1.5 as a handheld device, and we do not advocate the use of this class, considering that android has designed a task mechanism for us, we will not repeat it too much here. For the relevant reasons, refer to the following introduction:

6. Android also provides a processing method different from the thread, that isTask and asynctask, From openSource codeThe concurrent encapsulation allows developers to conveniently process these asynchronous tasks.

Extracted from:Http://www.cnblogs.com/playing/archive/2011/03/24/1993583.html

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.