I remember an interview experience with the Android client of iQiyi and Didi Dache. These questions from the interviewer made me feel a crit!

"It's uncomfortable enough! Do you want me to write it in a short book and share it? Listen, listen, that's my heartbroken voice"

The above is the conversation between me and my former colleague and friend . Just in this year’s Golden 9th Silver 10th , I seized the good opportunity of this interview and recruitment with great hope , but I did not expect to encounter unexpected events at the beginning. I have never interviewed two companies I like ( Didi and iQiyi ). The interview process can be regarded as the most...sad interview experience. He asked me to make out the face by sharing the pit to avoid attention when being interviewed interview friends, listening to his words, I put the failure of the surface by finishing a bit , plus the beautiful language of paragraph compiled this article. I hope my friends in the interview can perfectly avoid the pits I have been wading!

IQiyi Android client face analysis

1. Talk about the characteristics of the Java language and OOP ideas

This is described by comparison, such as object-oriented and process-oriented comparison. For the comparison of these two ideas, you can also give an example in development, such as the implementation of a player. The process-oriented implementation is to play the video function. Decompose into multiple processes.

For example, load the video address, get the video information, initialize the decoder, select the appropriate decoder to decode, read the decoded frame for video format conversion and audio resampling, and then read the frame for playback. This is a complete process , This process does not involve the concept of classes, and the biggest feature of object-oriented is the class, encapsulation inheritance and polymorphism are the core.

Similarly, take the player as an example, an object-oriented approach will encapsulate an object for each function, such as  Muxer, get video information, decoder, decode, format converter, video player, audio player devices , etc., each function corresponds to an object, the object is accomplished by a corresponding function, and follow the single responsibility principle, it is related to an object only thing

2. What are the differences between Activity, Window and View, and the characteristics of fragment?

How do the Activity, Window, and View display the interface together.

——Test site: Familiarity with the source code of the displayed process (view drawing process).
Activity The person who cuts the window grilles (controlling);
Window window (a model carried);
View window grilles (View to be displayed);
LayoutInflater scissors---cut the layout (drawings) into window grilles.

Features of fragment: The design of fragment is mainly to break the Activity interface including its logic into many independent modules, which facilitates the reuse of modules and more flexible assembly to present various interfaces.
1) Fragment can be used as a part of the Activity interface;
2) Multiple Fragments can appear in one Activity, and one fragment can be used in multiple Activities;
3) During Activity running, it can be dynamically added, deleted, and replaced Fragment.
4) Fragment has its own life cycle and can respond to input events.

3. How to implement high version api in low version SDK?

Two situations:
1) Generally, many new APIs of higher versions will find alternative implementations in the compatibility package. Such as fragment. Notification, there is a NotificationCompat class in the v4 compatibility package. If the backgroundTint and minSdk appearing in 5.0+ are less than 5.0, the detection error will be included. The v4 compatibility package DrawableCompat class.
2) Manual implementation without alternative implementation. For example: the water ripple effect of the control-a third-party implementation. Or remove this effect directly in the lower version.
3) Supplement: If minSDK is set but a higher version of API is used in the code, a detection error will occur. It is necessary to use declarative compilation detection strategies in the code, such as @SuppressLint and @TargetApi annotations to prompt the compiler to compile rules. @SuppressLint ignores detection; @TargetApi=23, will strictly match the SDK version according to the API used in your function, and give the corresponding compilation error prompt.
4) In order to avoid location errors, it is best not to use obsolete APIs. (Under normal circumstances, there will be no compatibility issues. This API method may be deleted at any time later; performance issues.)

4. View drawing process?

The main process of View drawing is divided into three stages: measure, layout and draw.

measure: Calculate the size according to the MeasureSpec passed by the parent view.
layout: According to the layout size and layout parameters obtained by the measure of the child View, place the child View in a suitable position.
draw: Draw the View object on the screen.

5. How does Handler execute from the perspective of Handler's source code?

These things are quite a lot. Then let's look at a chestnut first

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_http).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text();
            }
        });

    }

    private void text() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Handler handler1 = new Handler() {//为了说明问题的写法
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.e(TAG, "handle1: " + msg.what + "-thread1-" + Thread.currentThread().getName());
                    }
                };
                Message msg = new Message();
                msg.what = 2;
                handler1.sendMessage(msg);
                handler2.obtainMessage(1).sendToTarget();
                handler2.obtainMessage(4).sendToTarget();
                Looper.loop();
                Log.e(TAG, "loop 执行完毕");
                handler2.obtainMessage(3).sendToTarget();
            }
        }).start();
    }

    Handler handler2 = new Handler() {//普通写法
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "handle2: " + msg.what + "-thread2-" + Thread.currentThread().getName());
        }
    };
}

6. How to avoid OOM?

  • 1. Use a lighter data structure: For example, using ArrayMap/SparseArray instead of HashMap, HashMap consumes more memory, because it needs additional instance objects to record Mapping operations. SparseArray is more efficient because it avoids automatic boxing of Key Value. And unboxing operation after packing.

  • 2. The use of convenient enumeration can be replaced with static constants or annotation @IntDef

  • 3. Bitmap optimization: a. Size compression: Set appropriate scaling through InSampleSize b. Color quality: Set appropriate format, ARGB_6666/RBG_545/ARGB_4444/ALPHA_6, there is a big difference c.inBitmap: Use the inBitmap property to inform the Bitmap decoder Try to use the existing memory area. The newly decoded Bitmap will try to use the pixel data memory area occupied by the previous Bitmap in the Heap, instead of asking the memory to reapply for an area to store the Bitmap. Using this feature, even thousands of pictures only need to occupy the memory size of the number of pictures that can be displayed on the screen, but there are some restrictions on reuse, which are specifically reflected in: before Android 4.4, only the same size can be reused The memory of Bitmap, Android 4.4 and later versions only need to be smaller than the previous Bitmap. Before using the inBitmap parameter, each Bitmap object created will allocate a block of memory for its use. After using the inBitmap parameter, multiple Bitmaps can reuse a block of memory, which can improve performance.

  • 4. StringBuilder instead of String: In some cases, the code will need to use a lot of string splicing operations. In this case, it is necessary to consider using StringBuilder to replace frequent "+"

  • 5. Avoid creating objects in methods like onDraw, because it will quickly take up a lot of memory, causing frequent GC and even memory jitter

  • 6. Reducing memory leaks is also a way to avoid OOM

7. What are the scenarios and solutions for memory leaks?

  • 1. A static instance of a non-static internal class. A non-static internal class will hold a reference to an external class. If an instance of a non-static internal class is static, it will maintain the reference of the external class for a long time, and the organization will be recycled by the system. Solution Is using static inner class

  • 2. Multi-thread-related anonymous inner classes and non-static inner classes Anonymous inner classes also hold references to external classes. If time-consuming operations are performed in threads, memory leaks may occur, resulting in external classes that cannot be recycled until consumption When the task ends, the solution is to end the task in the thread when the page exits

  • 3. Handler memory leak The memory leak caused by Handler can also be summarized as caused by non-static internal classes. The internal messages of Handler are stored in MessageQueue. Some messages cannot be processed immediately, and they will exist for a long time, making the handler unable to Being recycled, if the handler is non-static, it will cause its external class to be unable to be recycled. The solution is 1. Use a static handler, and use weak references to handle external class references. 2. Remove messages from the message queue when exiting the page

  • 4. Context causes memory leaks. Determine whether to use Activity's Context or Application's Context according to the scene, because the life cycle of the two is different. For scenes (Dialog) that do not have to use Activity's Context, the Application Context is used. Singleton mode is the most common Scenarios where this leak occurs, for example, the Context passed in an Activity is referenced by a static class, resulting in failure to recycle

  • 5. Static View causes leakage. Using static View can avoid reading and rendering the View every time the Activity is started, but the static View
    will hold the reference of the Activity, which can not be recycled. The solution is to set the static View to when the Activity is destroyed null (Once the View is loaded into the interface, it will hold a reference to the Context object. In this example, the context object is our Activity. Declaring a static variable to refer to this View also refers to the activity)

  • 6. Memory leak caused by WebView As long as WebView is used once, the memory will not be released. Therefore, WebView has memory leak problems. The usual solution is to open a process for WebView and use AIDL for communication. Time to release

  • 7. If the resource object is not closed, such as Cursor, File, etc., buffers are often used internally, which will cause memory leaks. Be sure to close it and set the reference to null

  • 8. Objects in the collection are not cleaned up. The collection is used to save the objects. If the collection gets bigger and bigger, no reasonable cleanup is done, especially if the share collection is static

  • 9. Bitmap causes memory leaks. Bitmap takes up more memory, so it must be cleaned up in time when not in use to avoid static variables holding large bitmap objects.

  • 10. The listener is not closed. Many system services that require register and unregister need to be unregistered at the appropriate time, and manually added listeners need to be removed in time

Analysis of Didi Taxi Android Client

1. What about the life cycle of Activity?

Comprehensive life cycle analysis in typical situations

Life cycle analysis under abnormal conditions

2. How to keep the process alive?

  • a: Service will be restarted after it is set to START_STICKY kill (wait about 5 seconds), retransmit the Intent, and keep the same as before restarting

  • b: Set the process as the foreground process through startForeground, do the foreground service, the priority is the same level as the foreground application, unless the system memory is very scarce, the process will not be killed

  • c: Two-process Service: Let 2 processes protect each other, after one Service is cleaned up, the other process that has not been cleaned up can restart the process immediately

  • d: Use C to write a daemon process (ie, child process): The child process fork of the current process (Process) in the Android system is considered by the system as two different processes. When the parent process is killed, the child process can still survive and will not be affected (Android 5.0 and above are not feasible) Contact the manufacturer and add to the whitelist

  • e. When the screen is locked, start a one-pixel Activity

3. What are cold start and hot start? the difference? How to optimize and use scenarios?

App cold start: When the application starts, there is no process of the application in the background, then the system will re-create a new process and assign it to the application. This startup method is called cold start (the application process does not exist in the background).

Cold start because the system will re-create a new process assigned to it, so it will first create and initialize the Application class, then create and initialize the MainActivity class (including a series of measurement, layout, drawing), and finally display on the interface.

App hot start: When the application has been opened, but when the return key, home key and other keys are pressed, it returns to the desktop or other programs, and then reopens the app, this method is called hot start (the application already exists in the background) process).

Hot start will start from the existing process, so the hot start will not take the Application step, but directly go to MainActivity (including a series of measurement, layout, and drawing), so the hot start process only needs to create Just initialize a MainActivity, instead of creating and initializing the application cold start process when you click the app's start icon.

The Android system forks from the Zygote process to create a new process and assigns it to the application. After that, it creates and initializes the Application class, creates the MainActivity class, loads the windowBackground in the theme style, and sets the properties to MainActivity and configures the Activity level. Some attributes, inflate layout, and when the onCreate/onStart/onResume methods are all finished, the measure/layout/draw of contentView is finally displayed on the interface

The brief process of the life cycle of cold start:  Application construction method -> attachBaseContext() ->onCreate ->Activity construction method -> onCreate() -> Configure background and other operations in the main body ->onStart() -> onResume() -> Measurement, layout, drawing display

The cold start optimization is mainly a visual optimization, which solves the white screen problem and improves the user experience, so through the above cold start process. The optimizations that can be done are as follows:

  • 1. Reduce the workload of the onCreate() method
  • 2. Don't let Application participate in business operations
  • 3. Don't perform time-consuming operations in Application
  • 4. Don't save data in Application as static variables
  • 5. Reduce the complexity and level of layout
  • 6. Reduce the time consumption of the main thread

4. The reason for ANR?

  • 1. Time-consuming network access
  • 2. A large amount of data read and write
  • 3. Database operations
  • 4. Hardware operation (such as camera)
  • 5. When calling thread's join() method, sleep() method, wait() method or waiting for thread lock
  • 6. The number of service binders reaches the upper limit
  • 7. WatchDog ANR occurs in the system server
  • 8.Service is busy causing no response after timeout
  • 9. Other threads hold the lock, causing the main thread to wait for a timeout
  • 10. The termination or crash of other threads causes the main thread to wait

5. Tell me about the underlying implementation principle of LruCache?

The implementation of the Lru algorithm in LruCache is achieved through LinkedHashMap.

LinkedHashMap inherits from HashMap. It uses a doubly linked list to store the entry sequence relationship in the Map. For operations such as get, put, and remove, LinkedHashMap does not only do what HashMap does, but also adjusts the entry sequence list. In LruCache, the order of LinkedHashMap is set to LRU order to realize LRU caching. Every time get is called (that is, the picture is taken from the memory cache), the object is moved to the end of the linked list.

Calling put to insert a new object is also stored at the end of the linked list, so when the memory cache reaches the set maximum value, the object at the head of the linked list (the least used in the near future) is removed.

6. Tell me about the drawing process of the View tree?

When the Activity receives the focus, it will be requested to draw the layout. The request is handled by the Android framework. Drawing starts from the root node and measures and draws the layout tree.

The drawing process of the entire View tree is expanded in the performTraversals() function of the ViewRoot.java class. The work done by this function can be briefly summarized as whether the view size (measure) needs to be recalculated, whether the view location needs to be relocated (layout), and Whether to redraw (draw)

Because the length of the short book is limited, only part of it is shared. The full version of the interview, answer analysis, and Android interview review materials have been compiled by me into a (HD version) PDF. The PDF contains a lot of knowledge + many details, so it actually took a lot of time and energy than expected.

 

 

 

to sum up

In fact, for Android programmers, there are too many knowledge content and core technologies to learn. If you want to not be eliminated in the interview, you can only establish your own knowledge system in advance, plan your learning, and continue to learn. Only by improving yourself can you go on in the cold winter of the Internet market.

Remember, we always adapt to the environment, not the environment to adapt to us!

Friends who want to receive ① "Android Face Sutra Summary PDF" and ② "2020 Android Review Materials Summary PDF" for free study———— (here to join the free package to receive)

Guess you like

Origin blog.csdn.net/qq_39477770/article/details/108798569