Android and Handler

Source: Internet
Author: User

I. ThreadLocal analysis:

Literally, this Threadlocal is easy to misunderstand. Seriously, it is a local thread. In fact, this is a local information variable of the Thread, that is, a mechanism used to store unsafe variables in the thread. The analysis is as follows:

ThreadLocal class interface is very simple. There are only four methods. Let's take a look at it first:

Void set (Object value)

Set the value of the local variable of the current thread.

· Public Object get ()

This method returns the local variable of the thread corresponding to the current thread.

· Public void remove ()

Delete the local variable value of the current thread to reduce memory usage. This method is added to JDK 5.0. It should be noted that when the thread ends, the local variables of the thread will be automatically reclaimed, so explicitly calling this method to clear the local variables of the thread is not a required operation, but it can speed up memory recovery.

Protected Object initialValue ()

Returns the initial value of the local variable of the thread. This method is a protected method, apparently designed to overwrite the subclass. This method is a delayed call method. It is executed only once when the thread calls get () or set (Object) for 1st times. The default implementation in ThreadLocal directly returns a null value.

For each Thread and variable with the same name, we can create a new instance and save it to ThreadLocal with Thread. currentThread as the key. Get it through get () when we use it.

For Handler, mloler is usually stored

 

Ii. Whether the Handler is running in the subthread or the main thread

Let's take a look at the Handler constructor. Here there is a variable for the following operations:

Mlogoff = logoff. mylogoff ();

The preceding call is actually performed as follows:

Public static logoff mylogoff (){

Return sThreadLocal. get ();

}

That is, to obtain the Logoff of the current thread. In this case, the Handler runtime environment is not definite, but on which thread the handler is created and runs on the main thread when the main thread is created, otherwise, it is a subthread.

3. How to correctly start a subthread:

// Create a HandlerThread in the main thread

HandlerThread mHandlerThread = new HandlerThread ("XXX ");

// Step 2: Create your own Logoff

MHandlerThread. start ();

Create a subclass that inherits from Handler and assign the logoff class created above to this subclass. during creation, we create a subthread that is not running in the main thread. Otherwise, the Logoff of the thread that starts Handler is used by default.

Class myThread extends Handler {

Public myThread (low.logoff ){

Super (logoff );

}

Public myThread (){

Super ();

}

@ Override

Public void handleMessage (Message msg ){

// TODO Auto-generated method stub

Super. handleMessage (msg );

Switch (msg. what ){

Case 1:

Try {

Thread. sleep (20*1000 );

} Catch (InterruptedException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

Break;

}

}

}

// Initialization

MHandlerThread = new HandlerThread ("handler ");

MHandlerThread. start ();

// Create a subthread

MHandler = new myThread (mHandlerThread. getLooper ());

Iv. IntentService

IntentService inherits from the Service. It can run in the background without blocking the main thread. It is mainly attributed to opening a working thread, that is, creating a ServiceHandler inherited from the Handler, the handler's logoff is newly created. Unlike the Logoff of the main thread, it does not block the main thread.

Public abstract class IntentService extends Service {

}

When we start an IntentService through Intent, we first enter onCreate:

Public void onCreate (){

HandlerThread thread = new HandlerThread ("IntentService [" + mName + "]");

Thread. start ();

Mserviceloaders = thread. getLooper ();

MServiceHandler = new ServiceHandler (mserviceloader );

}

Is it true that a logoff is created through HandlerThread, and then assigned to the working thread ServiceHandler?

After IntentService is started, we start

Public int onStartCommand (Intent intent, int flags, int startId ){

OnStart (intent, startId );

Return mRedelivery? START_REDELIVER_INTENT: START_NOT_STICKY;

}

Public void onStart (Intent intent, int startId ){

Message msg = mServiceHandler. obtainMessage ();

Msg. arg1 = startId;

Msg. obj = intent;

MServiceHandler. sendMessage (msg );

}

The ServiceHandler function has a message processing mechanism. Here we call onHandleIntent for processing.

Public void handleMessage (Message msg ){

OnHandleIntent (Intent) msg. obj );

StopSelf (msg. arg1 );

}

5. How to destroy threads

1. Destroy Handler:

We know from the above: an important basis for enabling a sub-thread is to create a HandlerThread, where a new logoff will be created and then the Message will be processed through it. Handle the following when exiting:

OnDestroy (){

Super. onDestroy ();

// Set looper. quit of HandlerThread. The following example calls quit (the syntax is not considered here)

HandlerThread. quit ();

}

For messages sent in the form of Handler. post (Runnable), the above function should be:

Handler. removeCallbacks (mRunnable );

2. Destroy Thread

Currently, this function is used to set a global variable. When exiting, this variable is set to true. When the thread determines that this value is true, it exits the thread loop.


Author: kakaBack

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.