O(∩_∩)O~ Today brings you, 21 to Android advanced interview questions, understand these believe that you can go to the interview when the interviewer

So I’ve compiled this knowledge into a 983 PDF, from basic to advanced. Contains BATJ. Bytedance interview topics, Algorithms topics, High-end technology topics, Hybrid development topics,Java interview topics, Android,Java tips, to performance optimization. Threads. View.opencv.ndk. There are supplementary related video + study notes

Download more complete project. To be continued. The source code. Github. You can click about me to contact me for the full PDF github.com/xiangjiana/…

2019Android advanced interview questions summary

1. Describe design patterns and usage scenarios that you know

1). Builder mode:

Separating the construction of a complex object from its representation allows the same construction process to create different representations.

For example, in the development process of Camera, it may be necessary to set an initial Camera configuration, Camera orientation, flash on and off, image quality, etc. In this scenario, builder mode can be used

2). Decorator mode:

Adding additional responsibilities to an object dynamically gives decorator patterns more flexibility than subclassing in terms of adding functionality. The decorator pattern can enhance the functionality of a class without changing the structure of the existing class. For example, BufferedInputStream in Java wraps FileInputStream. For example, in development, if we need to add new functionality to our existing network framework, we can simply wrap another layer. Decorator pattern solves some of the problems of inheritance, such as the bloat of multiple layers of inherited code, making the code logic clearer

3). Observer model
4). Agent mode:
5). Appearance mode:
6). Singleton mode:
7). Producer-consumer model:

2. The characteristics of Java language and OOP thought

This by comparing to describe, such as object-oriented and process-oriented contrast, for the comparison of two kinds of thought, you can also give you an example in the development, the realization of the player, for example, is the implementation of the process oriented will broadcast video of this function is decomposed into multiple process, for example, the loading video address, video information, initialize the decoder, Choose appropriate decoder to decode, read after decoding frame of video format conversion and audio resampling, then reads the frame to play, this is a complete process, this process does not involve the concept of class, and the biggest characteristic is the object-oriented classes, encapsulation, inheritance and polymorphism is the core of the same players, for example, an object oriented way to do this, Will be for each function encapsulation out an object, such as said Muxer, video information, Decoder, Decoder, format converter, video player, audio player, etc., each function corresponds to an object, by the object to complete the corresponding functions, and follow the single responsibility principle, an object only do it related things

3. Talk about how threads are created in Java and how thread pools work.

There are three ways, or four ways, to create threads in Java

  • Inherit the Thread class to implement multithreading
  • Implement the Runnable interface
  • Implement Callable interface
  • By thread pool

How thread pools work: Thread pools reduce the number of times threads are created and destroyed, thereby reducing the consumption of system resources when a task is submitted to the thread pool

A. Check whether the core thread pool is full. If not, create a core thread to execute the task; otherwise, go to the next step. Check whether the work queue is full. If the work queue is not full, add it to the work queue. Otherwise, go to the next step c. Check whether the number of threads has reached the maximum. If not, create a non-core thread to execute the task. Otherwise, execute the saturation policy and raise an exception by default

4. Talk about handler

Handler, Message, Looper and MessageQueue constitute the Message mechanism of Android. After Handler is created, it can add messages to the Message queue through sendMessage, and then Looper can take messages out from MessageQueue continuously. Calls back to the handleMessage method of the Hander to enable thread communication.

The first is to create a Handler in the UI thread. There is no need to manually enable looper, because when the application starts, a looper for the current main thread is created in the ActivityThread main method and message queues are enabled. Message queues are an infinite loop. Why don’t infinite loops ANR? Android is event-driven. Looper.loop receives and processes events continuously. Every touch or Activity is controlled by Looper.loop. Once looper.loop ends, the application life cycle ends. We can think about when an ANR occurs, one, the event is not handled, two, the event is being handled, but it’s not completed in time, and the event that is being handled is a Looper, so we can only say that the processing of the event will cause an ANR if it blocks, not that the infinite loop of looper will cause an ANR, right

In this case, we need to manually call looper.prepare() and use looper.loop to read messages from the message queue. When we have read all the messages, The main thread is blocked. The child thread sends a message to the message queue and writes to the pipe file, the main thread is woken up, reads from the pipe file, the main thread is woken up just to read the message, and when the message is read, it goes to sleep again. Thus the loop does not have a significant drain on CPU performance.

5. Memory leak scenarios and solutions

1). Static instances of non-static inner classes

A non-static inner class holds a reference to an external class. If the instance of a non-static inner class is static, the reference to the external class will be maintained for a long time and the organization will be reclaimed by the system. The solution is to use static inner classes

2). Multithreaded related anonymous inner classes and non-static inner classes

Anonymous inner classes also hold references to external classes, and if a time-consuming operation is performed in a thread, a memory leak may occur, preventing the external class from being recycled until the time-consuming task ends, which is resolved by terminating the task in the thread when the page exits

3).Handler memory leak

Handler internal messages are stored in MessageQueue. Some messages cannot be processed immediately and exist for a long time, so that the Handler cannot be recycled. If the handler is non-static, then its external classes cannot be recycled, and the solution is 1. Use static handlers, external class references are handled with weak references. 2. Remove messages from the message queue when exiting the page

4).Context causes memory leaks

Depending on the scenario, decide whether to use the Activity Context or the Application Context, because they have different life cycles. The singleton pattern is the most common scenario where this leak occurs, such as when an Activity Context is passed in and referenced by a static class, making it impossible to reclaim

5). Static View causes leakage

Using a static View avoids reading and rendering the View every time you start an Activity, but a static View holds a reference to the Activity and cannot be recycled. The solution is to set the static View to NULL when the Activity is destroyed. (The View, once loaded into the interface, will hold a reference to a Context object. In this case, the Context object is our Activity, declare a static variable that refers to the View, This refers to the activity.

6). Memory leak caused by WebView

As long as WebView is used once, the memory will not be released, so WebView has the problem of memory leakage, the usual solution is to open a single process for WebView, use AIDL to communicate, according to the business needs at the appropriate time to release

7). The resource object is not closed

Cursors, files, etc., use internal buffers, which can leak memory. Be sure to close them and set references to NULL

8). Objects in the collection are not cleaned

Collections are used to hold objects, and if the collection gets larger and larger, it is not reasonably cleaned up, especially if the collection is static

9).Bitmap causes memory leaks

Bitmaps are memory intensive, so be sure to clean them up when not in use to avoid static variables holding large bitmaps

10). The listener is not closed

Many system services that require register and unregister need to be unregistered when appropriate, and manually added listeners need to be removed in time

6. How to avoid OOM?

1). Use more lightweight data structures: If you use ArrayMap/SparseArray instead of HashMap,HashMap is more memory intensive because it requires additional instance objects to record the Mapping operation, SparseArray is more efficient because it avoids automatic boxing of Key values and unboxing after boxing

2. The use of surface enumeration can be static constants or annotations@IntDefalternative

3. The Bitmap optimization:

  • Size compression: Set proper scaling with InSampleSize
  • Color quality: Set the appropriate format, ARGB_6666/RBG_545/ARGB_4444/ALPHA_6, vary widely
  • inBitmapUse:inBitmapProperty to tell the Bitmap decoder to try to use an existing memory area, the newly decoded Bitmap will try to use the pixel data memory area occupied by the previous Bitmap in the Heap, rather than asking the memory to request a new area to hold the Bitmap. Using this feature, even thousands of images only need to take up the memory size of the number of images that can be displayed on the screen. However, there are some limitations on reuse, which are embodied in: Prior to Android 4.4, you could only reuse the memory of a Bitmap of the same size, as long as the later Bitmap was smaller than the previous one. useinBitmapBefore the Bitmap object is created, a chunk of memory is allocated for each Bitmap object to useinBitmapAfter parameter, multiple bitmaps can reuse a single memory, which can improve performance

4.StringBuilder instead of String: In cases where code requires a lot of String concatenation, it’s worth considering StringBuilder instead of the frequent “+”

Avoid situations like thisonDrawCreate objects in this way, because it quickly takes up a lot of memory, causing frequentGCEven memory jitter

6. Reducing memory leaks is another way to avoid themOOMThe method of

7. Talk about the startup mode of an Activity, its life cycle, and the life cycle of two activities. If one Activity jumps to the other and then presses the Home button, what is the life cycle of the Activity

Boot mode

Standard mode: An Activity can have multiple instances. Each time an Activity is started, a new instance of the Activity is created, regardless of whether an instance of the Activity already exists in the task stack

SingleTop: When a SingleTop Activity is already at the top of the stack, no new instances are created. If the Activity is not at the top of the stack, new instances are created. If the Activity is already at the top of the stack, the system does not create a new instance of the Activity, as in singleTop mode. When an Activity already exists but is not at the top of the stack, the system moves the Activity to the top of the stack and removes the Activity above it from SingleInstance mode: SingleInstance is also a singleton, but unlike singleTask, which is an in-stack singleton, the system can have multiple Instances of singleTaskActivity. A singleInstanceActivity has only one instance in the system. When a singleInstanceActivity is started, the system creates a new task stack that has only one Activity life cycle

onCreate onStart onResume onPause onStop onDestroy

The life cycle of two Activity jumps

1. Start A oncreate-onstart-onresume

2. In A, start ActivityA onPause ActivityB onCreate ActivityB onStart ActivityB onResume ActivityA onStop

3. Return A from B (press the physical hardware return key) ActivityB onPause ActivityA onRestart ActivityA onStart ActivityA onResume ActivityB onStop ActivityB onDestroy

4. Return ActivityA onPause ActivityA onStop ActivityA onDestroy

8. Call scenario of onRestart

(1) After pressing the home button and then switching back, onRestart() is called. (2) After jumping from this Activity to another Activity, press the back button to return to the original Activity, and call onRestart(); (3) onRestart() is called when you switch from this Activity to another application and then back from another application; Let’s talk about the Activity life cycle of switching between horizontal and vertical screens, which method is used to save data, and the difference between the two. Trigger when to fetch data in that method etc.

9. SurfaceView, what is it? What is his method of succession? How it differs from View (from a source perspective, loading, drawing, etc.).

SurfaceView adopts double buffering mechanism to ensure smooth UI interface, and SurfaceView is not drawn in the main thread, but another thread to draw, so it does not interfere with THE UI thread;

SurfaceViewInherited from View, it has the following three main differences with View:

  • View doesn’t have double buffering underneath,SurfaceViewA;
  • View is mainly suitable for active updates, whileSurfaceViewThis works with passive updates, such as frequent refreshes
  • The View is going to update the UI in the main thread, andSurfaceViewIs refreshed in the child thread;SurfaceViewThe content is not in the application window, so you cannot use transformations (pan, scale, rotate, etc.). It’s hard to putListVieworScrollViewSome features of UI controls such asView.setAlpha()

View: display View, built-in canvas, graphic drawing function, touch screen event, button event function, etc.; The screen must be updated in the MAIN UI thread, which is slow.

SurfaceView: a view class extended based on the view, more suitable for 2D game development; Is a subclass of View, similar to the use of double slow mechanism, in a new thread to update the picture, so the refresh interface faster than View, Camera preview interface using SurfaceView.

GLSurfaceView: extended view class based on SurfaceView, dedicated to 3D game development view; SurfaceView subclass, openGL exclusive.

10. How to implement process survival

A: After the Service is set to START_STICKY kill, the Intent is restarted (wait about 5 seconds). The Intent remains the same as before the restart. StartForeground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground foreground Dual-process Service: two processes can protect each other. After one Service is cleared, the other processes can restart the process immediately. D: Write daemons (child processes) in C: In the Android system, the child processes of the current Process (Process) are considered as two different processes. When the parent process is killed, the child process can still live and not be affected (Android5.0 + is not available) contact the vendor to whitelist e. Start a one-pixel Activity while the screen is locked

11. Explain what cold startup and hot startup are, the difference, how to optimize, use scenarios, etc.

App cold start: When an application is started, the system creates a new process and assigns it to the application. This startup mode is called cold start (the application process does not exist in the background). Cold start Because the system will create a new process assigned to it, the Application class will be created and initialized, then the MainActivity class will be created and initialized (including a series of measurements, layout, drawing), and finally displayed on the interface.

App hot launch: When the app has been opened but is returned to the desktop or other applications by pressing the Back or Home button, it is called hot launch (the app process already exists in the background). The hot start process will start from the existing process, so the hot start process will not use the Application step, but directly use the MainActivity (including a series of measurements, layout, drawing), so the hot start process only needs to create and initialize a MainActivity. You don’t have to create and initialize the Application

When you tap the app’s startup icon, Android forks a new process from the Zygote process and assigns it to the app, This is done in turn by creating and initializing the Application class, creating the MainActivity class, loading properties like windowBackground in the Theme style Theme to the MainActivity and configuring some properties in the Activity hierarchy, the inflate layout, and when OnCreate/onStart/onResume method are covered before the final measure of contentView/layout/the draw is displayed in the interface on the cold start the brief process of the life cycle of: Application constructor — > attachBaseContext() — >onCreate — >Activity constructor — >onCreate () — > Configure operations such as backgrounds in the body — >onStart() — > onResume() – > Measure, layout, and display

Cold start optimization is mainly visual optimization, to solve the problem of white screen, improve user experience, so through the above process of cold start. The optimizations that can be made are as follows:

1. Reduce the onCreate() method’s workload 2. Do not let Application participate in business operations 3

12. Principle of three-level caching

When the Android terminal needs to obtain data, such as images in the network, it first looks up the data in the memory (press the key to search), and then looks up the data in the disk file or SQLite. If there is no data in the disk, it only obtains the data through the network

13. Underlying implementation principle of LruCache:

The Lru algorithm in LruCache is implemented through LinkedHashMap. LinkedHashMap inherits from HashMap. It uses a two-way linked list to store the order of entries in the Map. For get, PUT, remove and other operations, LinkedHashMap does some work to adjust the order of entries in the list. LruCache implements LRU caching by setting the order of the LinkedHashMap to LRU order, and moves the object to the end of the list each time a call to GET (that is, to fetch the image from the memory cache) is called. The call to put inserts new objects are also stored at the end of the list, so that when the memory cache reaches its maximum value, objects at the head of the list (least recently used) are removed.

14. Explain your understanding of the Collection class.
15. Ratio of older to newer JVM generations
16. What is the relationship between JVM, JRE and JDK? The Java Development Kit (JDK) is a product for Java developers. It is the core of the entire Java, including the Java runtime environment (JRE), Java tools, and Java basic class libraries.
17. What is your understanding of JNIEnv and JavaVM?
18. The difference between Serializable and Parcable?
19. Why does the cold start have a blank screen and a blank screen?
20. What are the principles and characteristics of threads in Android
21. ANR reason

For all the answers, please see the full PDF version (more full project downloads). To be continued. The source code. Github. You can click about me to contact me for the full PDF github.com/xiangjiana/…