Android provides a Handler Implementation Scheme for asynchronous message processing. Handler has many suitable applications and nuances, so that it achieves good results when used together with Thread and Service.
I. Differences between Handler and Thread. The Handler is in the same thread as the caller. If the Handler performs time-consuming operations, the caller thread will be blocked. Android UI operations are not thread-safe and must be executed in the UI thread. Android provides several basic solutions for processing UI operations in other threads, including runOnUiThread (Runnable) of the Activity ), both the post of View and the AsyncTask tool of version 1.5 adopt Handler, and the post of Handler does not actually start a new thread, instead, it directly calls the thread's run method, which is exactly what google is trying to do with a Handler.
Java code:
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
StartThread ();
// SendMessage ();
SystemClock. sleep (2000 );
SetContentView (R. layout. main );
}
Public void startThread (){
MThread. start ();
}
Public void sendMessage (){
MHandler mHandler = new MHandler ();
Message msg = mHandler. obtainMessage ();
Msg. sendToTarget ();
}
Class MHandler extends Handler {
Public MHandler (){
}
Public MHandler (low.l ){
Super (l );
}
@ Override
Public void handleMessage (Message msg ){
Int count = 0;
While (count ++ <Integer. MAX_VALUE ){
Log. d (TAG, "Rintail ");
}
}
}
Thread mThread = new Thread (){
@ Override
Public void run (){
Int count = 0;
While (count ++ <Integer. MAX_VALUE ){
Log. d (TAG, "Rintail ");
}
2. Handler does not process messages concurrently. A logoff reads the next Message only after processing a Message. Therefore, the Message is blocked. However, different logoff methods can achieve the goal of concurrency. In Service, onStart execution is also blocked. If a startService is used again before onStart is completed, it will also be blocked. If you want to execute onStart as soon as possible, you can use handler in onStart, because the Message sending is non-blocking. If the processing of different messages is concurrent, You Can instantiate Handler with different logoff values.