Android threads are used to update the UI, such as Thread, Handler, logoff, and TimerTask.

Source: Internet
Author: User

Method 1: (java is not recommended for android)

When I first came into contact with android Thread Programming, I used to be like java and tried to solve the problem using the following code.

New Thread (new Runnable (){
Public void run (){
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 = new Handler (){
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case TestHandler. GUIUPDATEIDENTIFIER:
MyBounceView. invalidate ();
Break;
}
Super. handleMessage (msg );
}
};


Class myThread implements Runnable {
Public void run (){
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 ();
}
}
}
}

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

Method 3: (java habits, not recommended)

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 class JavaTimer extends Activity {
 
Timer timer = new Timer ();
TimerTask task = new TimerTask (){
Public void run (){
SetTitle ("hear me? ");
}
};

Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

Timer. schedule (tasks, 10000 );

}
}

Method 4: (TimerTask + Handler)

In fact, this does not work, which is related to the thread security of Android! 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 on a regular basis. java. util. Timer, java. util. TimerTask, and android. OS. Handler are usually used. In fact, Handler itself provides the timed function.


Private Handler handler = new Handler ();
 
Private Runnable myRunnable = new Runnable (){
Public void run (){

If (run ){
Handler. postDelayed (this, 1000 );
Count ++;
}
TvCounter. setText ("Count:" + count );

}
};

Then, call

Handler. post (myRunnable );

Handler. post (myRunnable, time );

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

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 it as a UI 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.

For programmers who have been engaged in the development of J2EE, Thread is relatively simple. They can directly create and rewrite the run method anonymously and call the start method for execution. It can be inherited from the Runnable interface, but for the Android platform, the UI control is not designed as a thread security type. Therefore, some synchronization mechanisms need to be introduced to refresh it, in this case, Google designed Android by referring to the Win32 message processing mechanism.

1. you can use the postInvalidate () method in the thread to refresh a View as the base class interface, and provide some rewriting methods such as postInvalidate (int left, int top, int right, int bottom) to refresh a rectangular area and perform delayed operations, such as postInvalidateDelayed (long delayMilliseconds) or postInvalidateDelayed (long delayMilliseconds, int left, int top, int right, int bottom) method. The first parameter is in milliseconds.

2. of course, the recommended method is to use a Handler to handle this. You can call the postMessage or sendMessage method of the handler object in the run method of a thread. The Android Program maintains a message queue, this will be handled in turn. 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, and the Bundle object can encapsulate String, Integer, and Blob binary objects, we use the sendEmptyMessage or sendMessage method of the Handler object in the thread to transmit a Bundle object to the Handler processor. The Handler class provides the override method handleMessage (Message msg) to determine, and identify each piece of information through msg. what. 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, namely Task and AsyncTask. From the open source code, we can see that it is a Concurrent encapsulation, developers can easily process these asynchronous tasks.

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.