Knowledge points of Android basic interview questions in 2021

Knowledge points of Android basic interview questions in 2021

I. Introduction

  • Although it's already May, it's not the golden season, but no matter what month, there should be programmers looking for work. Even if it s not for job hunting, you can consolidate your knowledge points. After all, I clicked on this article .

  • Okay, not much to say, let's turn on the question mode.

2. brush questions

1. What is the life cycle of Activity and Fragment (without explanation, attach a picture)

2. The life cycle problem of switching Activity between horizontal and vertical screens

When the activity's android:configChanges is not set, each life cycle will be called back again when the screen is switched, and it will be executed once when the screen is switched horizontally, and twice when the screen is switched vertically. When setting Activity's android:configChanges= orientation , each life cycle will still be called when switching the screen. Switching between horizontal and vertical screens will only be performed once. When setting Activity's android:configChanges= orientation |keyboardHidden , each life will not be called again when switching the screen. Cycle, only the onConfigurationChanged method will be executed

3. Defects and problems of AsyncTask, talk about the principle.

What is AsyncTask?

  • AsyncTask is a lightweight asynchronous task class that can execute background tasks in the thread pool, and then pass the execution progress and final results to the main thread and update the UI in the main thread.

  • AsyncTask is an abstract generic class that provides three generic parameters: Params, Progress, and Result. Params represents the type of the parameter, Progress represents the execution progress and type of the background task, and Result represents the return result of the background task If AsyncTask does not need to pass specific parameters, then these three generic parameters can be replaced by Void.

About the thread pool:

  • The thread pool ThreadPoolExecutor corresponding to AsyncTask is shared within the scope of the process and is static, so Asynctask controls all subclass instances within the scope of the process. Due to this limitation, when using the default thread pool, if the number of threads exceeds the maximum capacity of the thread pool, the thread pool will burst (the default serial execution after 3.0 will not cause a problem). In response to this situation, you can try to customize the thread pool and use it with Asynctask.

About the default thread pool:

  • The thread pool in AsyncTask is a thread pool with a core thread number of CPU + 1, a maximum thread number of CPU * 2 + 1, a work queue length of 128, and a thread waiting queue with a maximum waiting number of 28, but the thread pool can be customized. The thread pool is handled by AsyncTask. The thread pool allows tasks to run in parallel. It should be noted that the data consistency problem in the case of concurrency, new data may be overwritten by old data. So if you want tasks to run serially, use SERIAL_EXECUTOR.

The difference between AsyncTask in different SDK versions:

  • The reason and improvement plan for calling the execute method of AsyncTask cannot execute the program immediately. By consulting the official documents, it is found that when AsyncTask was first introduced, asynchronous tasks were executed sequentially in a separate thread, which means that only one task is executed at a time and cannot be parallelized. Execution, starting from 1.6, AsyncTask has introduced a thread pool, which supports the simultaneous execution of 5 asynchronous tasks, which means that there can only be 5 threads running, and the excess threads can only wait, and the previous thread will not be scheduled until a certain execution is completed. And run. In other words, if the number of AsyncTask instances in the process exceeds 5, if the first 5 run for a long time, then the sixth one can only wait for the opportunity. This is a limitation of AsyncTask, and it cannot be resolved for versions prior to 2.3. If your application requires a large number of background threads to perform tasks, you can only give up using AsyncTask and create a thread pool yourself to manage Thread. It has to be said that although AsyncTask is more convenient to use than Thread, it can only run 5 threads at the same time, which greatly limits its role. You must carefully design your application, stagger the use of AsyncTask time, and try to divide it. If the number is guaranteed to be no more than 5, or you will encounter the problems mentioned above. It may be that Google is aware of the limitations of AsynTask. Since Android 3.0, it has made some adjustments to the AsyncTask API: only one thread is started to execute one task at a time, and then the second task is executed after it is over, which is equivalent to only one The background thread is executing the submitted task.

Points to note:

3.1. Memory leak

If AsyncTask is declared as a non-static inner class of Activity, then AsyncTask will retain a reference to Activity. If the Activity has been destroyed and the background thread of AsyncTask is still executing, it will continue to retain this reference in memory, causing the Activity to be unable to be recycled, causing a memory leak.

3.2. Life cycle

Many developers will think that an AsyncTask created in an Activity will be destroyed as the Activity is destroyed. However, it is not. AsynTask will continue to execute until the doInBackground() method is executed. Then, if cancel(boolean) is called, then the onCancelled(Result result) method will be executed; otherwise, the onPostExecute(Result result) method will be executed. If our Activity does not cancel the AsyncTask before it is destroyed, it may crash our application. Because the view it wants to handle no longer exists. Therefore, we must ensure that the task is cancelled before the event is destroyed.

3.3. Results are lost

Screen rotation or Activity being killed by the system in the background will cause the re-creation of the Activity. The previously running AsyncTask will hold a reference to the previous Activity. This reference is no longer valid. At this time, calling onPostExecute() to update the interface will no longer Take effect.

3.4. Parallel or serial

In versions before Android 1.6, AsyncTask is serial. In versions after 1.6, thread pools are used to handle parallel tasks. However, starting from Android 3.0, in order to avoid concurrency errors caused by AsyncTask, a thread is used to serialize Perform tasks. You can use the executeOnExecutor() method to execute tasks in parallel.

AsyncTask principle

  • There are two thread pools (SerialExecutor and THREAD_POOL_EXECUTOR) and a Handler (InternalHandler) in AsyncTask. The thread pool SerialExecutor is used to queue tasks, while the thread pool THREAD_POOL_EXECUTOR is used to actually execute tasks, and InternalHandler is used to switch the execution environment from the thread pool. To the main thread.
  • sHandler is a static Handler object. In order to switch the execution environment to the main thread, this requires that the sHandler object must be created in the main thread. Since static members are initialized when the class is loaded, this requires that the AsyncTask class must be loaded in the main thread, otherwise the AsyncTask in the same process will not work properly.

4. About onSaveInstanceState(Bundle outState) and onRestoreIntanceState(Bundle savedInstanceState)

  • These two methods are not the same as Android's life cycle methods onCreate, onStart, etc. When the user actively destroys the Activity, such as pressing the return button normally, the onSaveInstanceState() method will not be triggered. Only when the Activity has an accident Will be executed (for example, when the user presses the Home key, the onSaveInstanceState() method will not be executed)
  • onRestoreIntanceState(Bundle savedInstanceState) is used to echo data, similar to onCreate method, but there are also differences. onRestoreInstanceState(Bundle savedInstanceState) will be called only when the activity is indeed recycled by the system and the activity is recreated. At this time, the parameter savedInstanceState must not be null, and it will be executed after the onStart method. If the savedInstanceState is read in onRestoreInstanceState, it must have a value If the information stored in the Bundle is read in onCreate, it may be null.

5. The priority of the process in android

Foreground process: that is, the Activity or Service used by the activity that is interacting with the user. If the system memory is insufficient, the foreground process is killed at the latest

Visible process: it can be the Activity in the paused state (onPause) or the Service bound to it, which is visible to the user but cannot interact with the user due to loss of focus

Service process: The Service started using the startService method is running. Although it is not visible to the user, it is of concern to the user. For example, the user is listening to music on a non-music interface or a file downloaded from a non-download page; when the system needs space to run , The first two processes will be terminated

Background process: A program that is running and stopped by executing the onStop method, but is not what the user currently cares about, such as QQ hanging in the background. At this time, the process system will be killed first once it has no memory.

Empty process: A process that does not contain any application programs. Such a process system generally does not allow him to exist

6. Why does the Bunder pass object need to be serialized? What is the difference between Serialzable and Parcelable?

Because the bundle only supports basic data types when transferring data, it needs to be serialized and converted into a storable or transferable essential state (byte stream) when transferring objects. The serialized object can be transmitted between the network and IPC (such as Activity, Service, and Reciver that start another process), or it can be stored locally.

Serializable (included in Java): Serializable means serialization, which means converting an object into a storage or transferable state. The serialized object can be transmitted on the network or stored locally.

Parcelable (for android): In addition to Serializable, Parcelable can also achieve the same effect, but different from serializing the object, the realization principle of the Parcelable method is to decompose a complete object, and every part of the decomposition is It is the data type supported by Intent, which also realizes the function of transferring objects.

The differences are summarized as shown in the figure below:

7. Animation related

View animation:

  • The object of action is View, which can be defined by xml, and it is recommended that xml implementation is easier to read
  • Support four effects: translation, zoom, rotation, transparency

Frame animation:

  • Realized by AnimationDrawable, easy to OOM

Property animation:

  • Can act on any object, can be defined by xml, and introduced by Android 3. It is recommended that the code implementation is more flexible
  • Including ObjectAnimator, ValuetAnimator, AnimatorSet
  • Time interpolator: calculate the percentage of the current attribute change according to the percentage of time elapsed, the system presets interpolators such as uniform speed, acceleration, deceleration, etc.
  • Type estimator: calculate the changed attribute value according to the percentage of the current attribute change, the system presets type estimators such as integer, floating point, color value, etc.
  • Precautions for use: Avoid using frame animations, which are easy to OOM; stop animations when the interface is destroyed to avoid memory leaks; enable hardware acceleration to improve animation fluency
  • Hardware acceleration principle: share part of the work of the cpu to the gpu, and use the gpu to complete the drawing work; optimize the drawing speed from two aspects of work sharing and drawing mechanism

1. Calculate the attribute value

2. Set property values for the properties of the target object, that is, apply and refresh the animation

The calculation of attributes is divided into 3 processes:

Process one:

Calculate the elapsed fraction of the completed animation. In order to perform an animation, you need to create a ValueAnimator and specify the start, end, and duration of the target object's properties. During the entire animation process after calling start, ValueAnimator will calculate a score between 0 and 1 based on the completed animation time, which represents the percentage of completed animation for the animation. 0 means 0%, 1 means 100%.

Process two:

Calculate the interpolation (animation rate of change) interpolated fraction. When ValueAnimator has calculated the completed animation score, it will call the currently set TimeInterpolator to calculate an interpolated score. During the calculation process, the completed animation percentage will be added to the new interpolation calculation.

Process three:

Calculating the attribute value When the interpolation score calculation is completed, ValueAnimator will call the appropriate TypeEvaluator according to the interpolation score to calculate the attribute value in motion. The above analysis introduces two concepts: elapsed fraction and interpolated fraction.

Principles and characteristics:

1. Attribute animation:

Interpolator: The function is to calculate the percentage of attribute change based on the percentage of time elapsed

Estimator: On the basis of 1, this thing is used to calculate the class of how much the attribute has changed.

In fact, it is to use the interpolator and estimator to calculate the attributes of the View at each moment, and then realize the animation effect of the View by changing the attributes of the View.

2.View animation:

Only the image changes, the actual position of the view is still in the original place.

3. Frame animation:

After defining a series of pictures in xml, the animation is played using AnimatonDrawable.

The difference between them: the attribute animation is the real realization of the movement of the view, and the movement of the view by the tweening animation is more like drawing a shadow in different places, and the actual object is still in the original place. When the repeatCount of the animation is set to an infinite loop, if the animation is not stopped in time when the Activity exits, the attribute animation will cause the Activity to fail to release and cause a memory leak, but the tween animation is no problem. The tween animation realized by the xml file has a very high reuse rate. It has a good effect in the scene when the activity is switched, the window pops up, and so on. When using frame animation, you need to be careful not to use too many particularly large images, which may cause insufficient memory.

Why the property animation can still be clicked after moving: When playing the tween animation, the changes we see are only temporary. As for the attribute animation, what it changes will be updated to the matrix corresponding to this View, so when the ViewGroup dispatches an event, it will correctly convert the current touch coordinates into the coordinates after the matrix change. This is why The reason why playing the tween animation does not change the touch area.

8. New features of Android from 5.0 to 11.0

Android5.0 new features

MaterialDesign style

Supports 64-bit ART virtual machine (the ART virtual machine introduced in 5.0, which was Dalvik before 5.0. The difference is: Dalvik, every time it runs, the bytecode needs to be converted into machine code (JIT) by a just-in-time compiler. ART , When the application is installed for the first time, the bytecode will be pre-compiled into machine code (AOT))

Notification details can be designed by users

New features of Android 6.0

Dynamic rights management

Support fast charging switch

Support folder drag and drop application

Camera new professional mode

New features in Android7.0

Multi-window support

V2 signature

Enhanced Java8 language mode

Night mode

Android8.0 (O) new features

Optimization notification

Notification Channel (Notification Channel) Notification flag Sleep notification timeout notification setting notification clear

Picture-in-picture mode: Activity setting android:supportsPictureInPicture in the list

Background restrictions

Auto-fill frame

System Optimization

New features of Android9.0(P)

Indoor WIFI positioning

"Liu Hai" screen support

Security enhancement

Android10.0 (Q) new features

Night mode: All applications including mobile phones can be set to dark mode.

Desktop mode: Provides a PC-like experience, but it is far from replacing the PC.

Screen recording: Long press "Screen Snapshot" in the "Power" menu to turn it on.

Android11.0 (R) new features

privacy protection

Optimized folding device support

Optimize 5G experience

Mandatory apps to call the built-in camera: The use of third-party camera apps is not affected. Users can still use third-party camera apps to take photos and videos, and only the calling permissions are blocked.

9. About the principles and differences of several types of parsed xml in android?

DOM analysis


  • The XML tree is completely stored in memory, so its data structure can be directly modified.
  • You can access any node in the XML tree at any time through this parser.
  • The API of the DOM parser is relatively simple to use.


  • If the size of the XML document is relatively large, reading the document into memory does not consume system resources.

scenes to be used:

  • DOM is the official W3C standard for representing XML documents in a platform- and language-independent way.
  • DOM is a collection of nodes organized in a hierarchical structure. This hierarchy allows developers to find specific information in the tree. Analyzing the structure usually requires loading the entire document and constructing the hierarchy before any work can be done.
  • DOM is based on an object hierarchy.

SAX analysis


  • SAX has relatively low memory requirements because it allows developers to determine the tags to be processed. Especially when developers only need to process part of the data contained in the document, SAX's ability to expand is better reflected.


  • When using SAX for XML parsing, it needs to be executed sequentially, so it is difficult to access different data in the same document. In addition, the parsing and coding procedures based on this method are relatively complicated.

scenes to be used:

  • This method is very effective when the amount of data is very large, and you do not need to traverse or analyze all the data rows of the document. This method does not read the entire document into the memory, but only needs to read the document mark required by the program Just place.

Xmlpull analysis

  • Android SDK provides xmlpullapi, xmlpull and sax are similar, it is based on stream (stream) operation file, the latter according to the node event callback handler written by the developer. Because it is based on stream processing, so xmlpull and sax are more memory resources, It will not display all nodes in the memory in the form of an object tree like dom.xmpull is more concise than sax and does not need to scan the entire stream.

10. The difference between packaging Jar and aar

  • There is only code in the Jar package. There is not only code in aar but also resource files, such as drawable files and xml resource files. For some infrequently changed Android Library, we can directly reference aar to speed up the compilation.

11. Interpret the Handler message mechanism

The Android message loop flow chart is as follows:

The main roles involved are as follows:

  • message: message.
  • MessageQueue: Message queue, responsible for the storage and management of messages, and responsible for the management of Messages sent by Handler. Reading will automatically delete messages, and there are advantages in singly linked list maintenance, insertion and deletion. In its next() method, it will loop indefinitely, constantly judging whether there is a message, and return the message and remove it if there is.
  • Looper: Message looper, responsible for associated threads and message distribution. Under this thread, Message is obtained from MessageQueue and distributed to Handler. When Looper is created, a MessageQueue will be created. When the loop() method is called, the message loop will start, which will continue. Call the next() method of messageQueue, and process it when there is a message, otherwise it will be blocked in the next() method of messageQueue. When Looper's quit() is called, it will call messageQueue's quit(). At this time, next() will return null, and then the loop() method will exit.
  • Handler: Message processor, responsible for sending and processing messages, facing developers, providing APIs, and hiding the details behind the implementation.

The cyclic flow of the entire message is summarized as follows:

1. Handler sends a message to MessageQueue via sendMessage().

2. Looper continuously extracts the Message of the trigger condition through loop(), and hands the Message to the corresponding target handler for processing.

3. The target handler calls its own handleMessage() method to process the Message.

In fact, in the entire message loop process, not only the Java layer participates, but a lot of important work is done in the C++ layer. Let's look at the calling relationship of these classes.

Note: The dotted line indicates the association relationship, and the solid line indicates the call relationship.

Among these classes, MessageQueue is the bridge between the Java layer and the C++ layer. The related functions of MessageQueue and Looper are all completed through the Native method of MessageQueue, while the other classes connected by the dotted line only have an association relationship, and there is no direct call relationship. They are related. The bridge is MessageQueue.


  • Messages sent by Handler are stored and managed by MessageQueue, and Looper is responsible for callback messages to handleMessage().
  • The thread conversion is done by Looper, and the thread of handleMessage() is determined by the thread of the caller of Looper.loop().

The cause of memory leak caused by Handler and the best solution

Handler allows us to send delayed messages. If the user closes the Activity during the delay, the Activity will be leaked. This leak is because the Message will hold the Handler, and because of the characteristics of Java, the inner class will hold the outer class, so that the Activity will be held by the Handler, which will eventually cause the Activity to leak.

Solution: Define Handler as a static internal class, hold the weak reference of Activity internally, and call handler.removeCallbacksAndMessages(null) in Acitivity's onDestroy() to remove all messages in time.

Why can we directly use Handler in the main thread without creating Looper?

Usually we think of ActivityThread as the main thread. In fact, it is not a thread, but the manager of the main thread operation. The Looper.prepareMainLooper() method is called in the ActivityThread.main() method to create the Looper of the main thread, and the loop() method is called, so we can directly use the Handler.

Therefore, we can use the Callback interception mechanism to intercept Handler messages. Such as the processing of Hook ActivityThread.mH in most plug-in frameworks.

What can the Callback hidden in the Handler do?

Handler.Callback has the priority to process messages. When a message is processed and intercepted by Callback (returns true), then the handleMessage(msg) method of Handler will not be called; if Callback processes the message but not intercepted, then It means that a message can be processed by Callback and Handler at the same time.

The best way to create a Message instance

In order to save overhead, Android has designed a recycling mechanism for Message, so we try to reuse Message when using it to reduce memory consumption:

Through the static method Message.obtain() of Message;

Through the Handler public method handler.obtainMessage().

Does the infinite loop of the main thread running all the time consume CPU resources?

No, here is the Linux pipe/epoll mechanism. Simply put, when the MessageQueue of the main thread has no messages, it is blocked in the nativePollOnce() method in the of the loop. At this time, the main thread will release the CPU. The resource enters the dormant state until the next message arrives or a transaction occurs, and the main thread is awakened to work by writing data to the write end of the pipe. The epoll mechanism used here is an IO multiplexing mechanism that can monitor multiple descriptors at the same time. When a descriptor is ready (read or write ready), the corresponding program is immediately notified to read or write operations. The essence is Synchronous I/O, that is, reading and writing are blocking. Therefore, the main thread is mostly dormant and does not consume a lot of CPU resources.

How does handler postDelay realize this delay?

handler.postDelay does not wait for a certain period of time before putting it into the MessageQueue, but directly enters the MessageQueue, and is implemented by combining the time sequence of the MessageQueue and the wake-up method.

12. What should I pay attention to when using Bitmap?

1. To select the appropriate picture specifications (bitmap type):

ALPHA_8 Each pixel occupies 1byte memory
ARGB_4444 Each pixel occupies 2byte memory
ARGB_8888 Each pixel occupies 4byte memory (default)
RGB_565 Each pixel occupies 2byte memory

2. Reduce the sampling rate. To use the BitmapFactory.Options parameter inSampleSize, first set options.inJustDecodeBounds to true, just to read the size of the picture, and compare the size of the picture with the size to be displayed after obtaining the size of the picture, and calculate the specific value of inSampleSize through the calculateInSampleSize() function. After getting the value. options.inJustDecodeBounds is set to false to read image resources.

3. Reuse memory. That is, through soft references (reclaimed when the memory is not enough), the memory block is reused, and there is no need to re-apply a new memory for this bitmap, which avoids a memory allocation and recycling, thereby improving operating efficiency.

4. Use the recycle() method to recover memory in time.

5. Compress pictures.

13. Are there any restrictions on the data transmitted by broadcasting, how many are they, and why are they restricted?

Intent has a size limit when transferring data, which is approximately limited to 1MB. When you use Intent to transfer data, you actually go through inter-process communication (IPC). Inter-process communication requires copying data from the kernel to the process. A process has a buffer for receiving kernel data, the default is 1M; if the data passed at a time exceeds the limit, an exception will occur.

Different manufacturers may behave differently. It is possible that the manufacturer has modified the size of this limit, or the same object may have different sizes on different machines.

To transfer big data, you should not use Intent; consider using ContentProvider or directly anonymously sharing memory. In simple cases, you can consider segmented transmission.

14. There are generally several types of broadcast registration, and what are the advantages and disadvantages of each?

The first is the resident type (static registration): when the application is closed, if there is information broadcast, the program will also be called by the system and run by itself.

The second type is not permanent (dynamic registration): broadcast will follow the life cycle of the program.

Dynamic registration

  • Advantages: In the android broadcast mechanism, the dynamic registration priority is higher than the static registration priority, so if necessary, it is necessary to dynamically register the broadcast receiver.
  • Disadvantages: When the activity used for registration is turned off, the broadcast is invalidated.

Static registration

  • Advantages: There is no need to worry about whether the broadcast receiver is turned off, as long as the device is turned on, the broadcast receiver is turned on.
  • Disadvantages: longer survival time, a certain loss of power and performance of the mobile phone.

15. There are generally several types of service startups, how to communicate between services and activty, and how to communicate between services and services


onCreate()--->onStartCommand() ---> onDestory()

If the service is already started, onCreate() will not be executed repeatedly, but onStartCommand() will be called. Once the service is started, it has nothing to do with the caller (opener). The opener quits, the opener hangs up, and the service is still running in the background for a long time. The opener cannot call methods in the service.


onCreate() --->onBind()--->onunbind()--->onDestory()

Start the service in bind mode, bind the service, and the caller hangs up, and the service also hangs up. The binding person can call methods in the service.


  • Through the Binder object.
  • Via broadcast.

16. Several modes of LaunchMode

standard : Create a new Activity.

singleTop : The top of the stack is not an Activity of this type, create a new Activity. Otherwise, the onNewIntent() method will be used.

singleTask : If there is no activity of this type in the rollback stack, create an Activity, otherwise, it will go to the onNewIntent method and clear the Activity in the task station.

singleInstance : In the rollback stack, there is only this activity, and no other activities.

3. finally

Space is limited, so I won t write so much. If you re interested, search on the WeChat official account: develop small dry goods. There are a full version of Android basic interview questions, a total of 4, and many Android and java pdf format books, all for free!

Or scan the code directly on WeChat to follow

We hope you can join,,,