I have been asked this question two or three times before BAT. Why do you like to ask this question? Because there are a lot of questions out there that are not easy to answer.

First of all ask

What’s the difference between IntentService and Service?

A Service runs on the main thread. Using a Service to perform a time-consuming task will block the main thread, resulting in ANR. The Service ANR time is 20 seconds for the front serviceservice and 200 seconds for the back serviceService.

IntentService starts the child thread, overriding the processing logic in the onHandleIntent method without raising an ANR.

If that’s all you get for senior positions, it’s highly likely

Then you should answer

How does IntentService work?

IntentService the entire class is less than 100 lines of code, so let’s take a look at the core source code

Handler is bound to the child thread of the HandlerThread, looper mServiceLooper, OnStart sendMessage calls onHandleIntent to perform the override logic.

Well, this is definitely the time to answer

What is HandlerThread and how is it implemented?

HandlerThread is just what the name suggestsThe Handler and the ThreadHandlerThread inherits the looper of the prepare child Thread from the run method and stores it in mLooper for external access.

So handlerThreads are good for serial tasks.

The area marked with the arrow in the figure above is synchronize, which raises a question. If you answer this question, you can tell that you have read the source code

What is the role of synchronized in HandlerThread?

The getLooper method is called to get the current thread’s looper (see IntentService’s onCreate), and then the synchronized block waits () if mLooper is empty, waiting for mLooper assignment. The assignment of mLooper is at the first arrow, after which notifyAll wakes up and returns the assigned mLooper.

What is the difference between synchronized and lock? How does it work? Or how many types of locks does synchronized have? Do you understand the expansion process? Can diverge a lot of problems, simple synchronized content can be a separate talk.

Warm prompt

IntentService The new SDK version is deprecated. The new SDK version allows you to consider using WorkManager or JobIntentService, but does not prevent you from learning about it.

To summarize

IntentService(Service+HandlerThread+Handler)

HandlerThread(extends Thread+handler+prepare looper)

It is very important to build their own knowledge system, “then you tell me the” series is hope the some knowledge to string together, can better help you understand and associated memory, rather than just share a scattered point and is actually my own at ordinary times notes, hope you can like this series, can be a lot of thumb up.