Android threads are used to update the UI----thread, Handler, Looper, TimerTask, etc.

Source: Internet
Author: User

Method One: (Java habits, not recommended in Android)

Just beginning to touch Android threading programming, habits like Java, trying to solve the problem with the following code

new Thread ( new Runnable () {
public void run () {
Myview.invalidate ();
}
}). Start ();

Functionality can be implemented to refresh the UI interface. This is not possible, however, because it violates the single-threaded model: Android UI operations are not thread-safe and must be executed in the UI thread.

Method Two: (Thread+handler)

After reviewing the documentation and Apidemo, it was found that the common approach was to use handler to implement UI thread updates.

Handler to handle UI updates based on received messages. The thread thread issues a handler message informing the update UI.

Handler MyHandler = new Handler () {
public void handlemessage (Message msg) {
Switch (msg.what) {
Case Testhandler.guiupdateidentifier:
Mybounceview.invalidate ();
break;
}
Super. Handlemessage (msg);
}
}; ClassMyThreadImplementsRunnable {
Public voidRun () {
While (! Thread.CurrentThread (). isinterrupted ()) {

Message message = new Message ();
message.what = Testhandler.guiupdateidentifier;

Testhandler. This.myhandler.sendmessage (message);
try {
Thread.Sleep ( 100);
} catch (Interruptedexception e) {
Thread.CurrentThread (). interrupt ();
}
}
}
/span>

Above method Demo View: http://rayleung.javaeye.com/blog/411860

Method Three: (Java habit, not recommended)

In the Android platform, you can use the TimerTask class that comes with Java on a recurring basis, and TimerTask is less for resource consumption than for thread, In addition to using the Alarmmanager with Android, using the timer timer is a better solution. We need to introduce import java.util.Timer; and import Java.util.TimerTask;

Public ClassJavatimerExtendsActivity {

Timer Timer= NewTimer ();
TimerTask Task= new TimerTask () {
Span style= "color: #0000ff;" >public void run () {
Settitle ( "hear me?" );
}
};

public void< Span style= "color: #000000;" > OnCreate (Bundle savedinstancestate) {
super Setcontentview (R.layout.main);

Timer.schedule (task, 10000
}
} /span>

Method Four: (TimerTask + Handler)

It's not really going to work, it's about the thread safety of Android! The timer function should be realized by cooperating with handler!

Public ClassTesttimerExtendsActivity {

Timer Timer= NewTimer ();
Handler Handler= new Handler () {
Span style= "color: #0000ff;" >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< Span style= "color: #000000;" > Message ();
message.what = 1< Span style= "color: #000000;" >;
Handler.sendmessage (message);
}
};  
public void onCreate (Bundle savedinstancestate) {
Super. OnCreate (savedinstancestate);
Setcontentview (R.layout.main);
timer.schedule (Task, 10000);
}
}

Method Five: (Runnable + Handler. postdelayed (runnable,time))

Regularly update the UI on Android, usually using java.util.Timer, java.util.TimerTask, Android. Os. Handler combination. In fact, handler itself has provided a timed function.

PrivateHandler Handler= NewHandler ();

PrivateRunnable myrunnable= new Runnable () {
public void run () {

if handler.postdelayed (this, 1000);
Count++;
}
Tvcounter.settext ( "count: " + count);

}
};

And then call it somewhere else.

Handler.post (myrunnable);

Handler.post (Myrunnable,time);

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

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

Knowledge Point Summary Supplement:

Many novice Android or Java developers are still confused with thread, Looper, handler, and message, derived from Handlerthread, Java.util.concurrent, Task, Asynctask as the current literature on the market did not talk about these issues, today on this issue to do a more systematic summary. The service, activity, and broadcast we create are a primary thread processing, which we can understand as a UI thread . However, in the operation of some time-consuming operations, such as I/O read and write large file read and write, database operations and network download takes a long time, in order not to block the user interface, a ANR response prompt window, this time we can consider using thread threads to solve.

For programmers who have engaged in J2ME development, the thread is simpler, directly anonymous create rewrite the Run method, call the Start method execution. or inherited from the Runnable interface, but for the Android platform the UI controls are not designed to be thread-safe , so you need to introduce some synchronous mechanisms to refresh them. Google in the design of Android when the reference to the next WIN32 message processing mechanism.

1. For a thread to refresh a view-based interface, you can use the Postinvalidate () method to process it in the threads, which also provides some overriding methods such as postinvalidate (int left,int top, int Right,int bottom) to flush a rectangular area, and delay execution, such as postinvalidatedelayed (long delaymilliseconds) or postinvalidatedelayed (long Delaymilliseconds,int left,int top,int Right,int Bottom) method, where the first parameter is a millisecond

2. Of course, the recommended method is to handle These through a handler, you can invoke the handler object's PostMessage or SendMessage method in a thread's Run method, The Android program maintains a message queue that will handle these rotation, and if you are a WIN32 programmer can understand these message handling well, but there is no way to pretranslatemessage these internal interferences with Android.

3. What is Looper? , in fact, every thread in Android follows a looper,looper to help thread maintain a message queue, but Looper and handler have nothing to do with it. We can see from the open source code that Android also provides a thread inheriting class Handerthread can help us to handle, in the Handlerthread object can get a Looper object control handle through the Getlooper method, We can map its Looper object to a handler to implement a thread synchronization mechanism, Looper object execution needs to initialize Looper.prepare method is the problem we saw yesterday, while the release of resources, Use the Looper.release method.

What is 4.Message on Android? For Android handler can pass some content, through the bundle object can encapsulate string, integer and Blob binary object, we through the thread Use the Sendemptymessage or SendMessage method of the handler object to pass a bundle object to the handler processor . The handler class provides an overriding method Handlemessage (Message msg) to judge by Msg.what to differentiate each piece of information . The bundle is unpacked to implement the handler class to update the contents of the UI thread to implement the refresh operation of the control. Related handler object about message sending Sendxxxx related methods are as follows, and there are postxxxx related methods, these and Win32 the rationale is basically consistent, one for send after the direct return, one for processing before returning.

5. Java.util.concurrent object analysis, for programmers in the past Java development will not be unfamiliar with concurrent objects, he is the JDK 1.5 new important features as handheld devices, we do not advocate the use of this class, Considering that Android is a task mechanism that we have designed, there is no too much to repeat here, the related reasons refer to the following description:

6. In Android, there is a different threading approach, task and Asynctask, which can be seen in the open source code for the concurrent package, and developers can easily handle these asynchronous tasks.

Excerpt from: http://www.android123.com.cn/androidkaifa/422.html

Android threads are used to update the UI----thread, Handler, Looper, TimerTask, etc.

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.