I found that the interviewer kept asking questions about Android! (Organized)

beginning

In order to prepare for the interview, I reviewed some of the principles of Android, and successively summarized some interview-related things. Because I haven't written interviews and other blogs for too long, I want to share the knowledge of Android interviews today.

But I’m so helpless (灬ꈍ ꈍ灬) . I interviewed more than ten major factories in Beijing and Shenzhen (remote video interview) and only got offers from LeTV and Xiaomi . In general, Xiaomi’s salary ratio is higher than that a little. After listening to a friend’s suggestion, I chose Xiaomi, planning to make a transition to audio and video in the future.

First review from the basic principles of Android, and then organize some knowledge that needs to be mastered for an advanced salary increase in interviews, ** (including the knowledge points of Android expansion that Dachang interviewers are always asking for) ** have been collected and organized into PDF, Sharing it hopes to help everyone find a good job between gold and silver.

1. Android related

1. mvc mvp mvvm three architecture modes (Tencent)

mvc : A mode of separation of business logic, data, and interface. In simple terms, it is to manipulate the data of the model layer through the controller and return it to the view for display.

Activity is not a standard controller. As the complexity of the interface logic interaction increases, the responsibilities of the activity class continue to increase and become bloated.
View and model are coupled with each other, which is not conducive to development.

mvp : The presenter layer is mainly proposed as a bridge between view and model.

The program logic is processed in the presenter, which completely separates the view and the model, and does not allow communication between them.

mvvm : Mainly changing the presenter to the viewmodel, which is similar to mvp, except that the viewmodel is two-way bound with the view and the model.

Data binding is used

2. Android system structure level

The Android system architecture is divided into 5 layers, from bottom to top, the Linux kernel layer, the hardware abstraction layer, the system runtime layer (Native), the application framework layer, and the application layer.

  • Linux kernel layer : The core of Android is based on the Linux kernel. On this basis, Android special drivers (such as Binder), system security, memory management, process management, etc. are added.

  • Hardware Abstraction Layer (HAL) : It doesn't work with the core, you have to run on the corresponding hardware to realize your own value. The hardware abstraction layer is the interface between the hardware and the Linux kernel. The purpose is to abstract the hardware and protect the intellectual property rights of hardware manufacturers (Linux has an open source agreement)

System runtime layer: how to manipulate the hardware and display images to the screen? This layer does this. It is divided into two parts, the C++ library and the Android runtime.

  • C++ library : It is used by different components in the Android system, and can be used by developers through the application framework layer. The following are the main libraries:

  • Android Runtime : ART virtual machine (after 5.0, the Dalvik virtual machine was replaced by ART). When the application is first installed, ART will precompile the bytecode into machine code and store it locally, so that the application does not need to be run each time Compilation is executed (Dalvik is compiled on the fly every time it is opened), typically with space for time

  • Application framework layer : Framework layer. This layer of code is written in java and provides APIs for developers.

  • Application layer

3. Activity start mode and application scenarios (Netease, Baidu)
  • standard : The default mode, creating a new Activity will create a new activity instance in the stack.
  • singleTop : Stack-top multiplexing mode. Compared with standard, stack-top multiplexing can effectively reduce the resource consumption of repeated activity creation. Login page, payment page such as wxpay
  • singleTask : Singleton mode in the stack. There is only one activity instance in the stack. There is an activity instance in the stack. Start this * **activity in other activities. Android directly kicks other activity instances on this instance out of the stack for GC. Main page, WebView page, scan page, payment interface
  • singleInstance : Open up a new stack to store activity. System application such as launcher, lock screen key, caller ID and so on.

4. The method of communication between Android processes (Xiaomi, Didi)

1. Broadcast broadcast, when a program sends a broadcast to the system, other applications can only passively receive broadcast data
2. Content Provider, the way of data sharing between multiple applications (data sharing across processes), applications You can complete the addition, deletion, modification, and checking of data. The Android system itself also provides a lot of Content Providers, such as audio, video, and contact information.
3. Through the AIDL file, the AIDL is also through the binder to achieve inter-process communication.
4.socket

1. Traditional IPC communication method

The Android system is based on the Linux kernel. Linux provides IPC mechanisms such as pipes, message queues, shared memory, and sockets. So why does Android still provide Binder to implement IPC? Mainly based on performance, stability and security considerations.

Performance : Socket, as a general interface, has low transmission efficiency and high overhead. It is mainly used for cross-network process communication. Message queues, shared memory, and pipelines use a store-and-forward model, and data copies need to be at least twice. Although shared memory does not need to be copied, it is complicated to control and difficult to use. The binder only needs to be copied once, which is second only to shared memory in performance.

Stability : Binder is based on the C/S architecture. Whatever needs of the client (Client) are left to the server (Server) to complete, the structure is clear, the responsibilities are clear and independent, and the natural stability is better.

Security : Android assigns its own UID to each installed APP, so the UID of the process is an important sign to identify the identity of the process. Traditional IPC can only be used by users to fill in UID/PID in data packets, but this is unreliable and easy to be used by malicious programs. Reliable identification can only be added in the kernel by the IPC mechanism. Secondly, traditional IPC access points are open. As long as you know the programs of these access points can establish a connection with the opposite end, no matter what, malicious programs cannot be prevented from obtaining a connection by guessing the recipient's address.

2. The principle of traditional IPC communication

The usual practice is that the message sender stores the data to be sent in the memory buffer and enters the kernel mode through a system call. Then the kernel program allocates memory in the kernel space, opens up a kernel buffer area, and calls the copy_from_user() function to copy the data from the memory buffer area in the user space to the kernel buffer area in the kernel space. Similarly, the receiving process opens up a memory buffer area in its user space when receiving data, and then the kernel program calls the copy_to_user() function to copy the data from the kernel buffer area to the memory buffer area of ​​the receiving process. In this way, the data sender process and the data receiver process have completed a data transmission, and we say that an inter-process communication has been completed.

A data transfer needs to go through: memory buffer area --> kernel buffer area --> memory buffer area, which requires 2 data copies

The buffer area for receiving data is provided by the data receiving process, but the receiving process does not know how much space is needed to store the data to be transferred, so it can only open up as much memory space as possible or call the API to receive the message header first to get the message body The size of these two methods is either a waste of space or a waste of time.

3. Binder IPC implementation

The memory mapping involved in the Binder IPC mechanism is implemented by mmap(), which is a method of memory mapping in the operating system . Simply speaking, memory mapping is to map a memory area of ​​user space to kernel space. After the mapping relationship is established, the user's modification of this memory area can be directly reflected in the kernel space; conversely, the modification of this area in the kernel space can also be directly reflected in the user space.

5. ContentProvider design pattern

6. The realization method of multithreading (the similarities and differences between synchronized and lock)

  1. Inherit the Thread class to create threads
  2. Implement the Runnable interface to create threads, this method is recommended, and runnable can be reused
  3. Implement the Callbale interface and create a thread with a return value through the FutureTask wrapper

synchronized

In terms of usage, it is a keyword of java. Generally, we don't need to pay much attention to the release of his lock. The lock will be automatically released after the code is executed or an error is reported, and the state of the lock cannot be judged.

lock

It is an interface, we use ReentrantLock more, there are multiple ways to acquire the lock, trylock can directly return the success or failure of the acquisition, the thread does not have to wait all the time. The lock must be released in finally.

7. Talk about the event distribution mechanism of View

Why should there be event distribution

Note: Quoting the blog of God G

The view in Android is a tree structure, and the views may overlap. When there are multiple views in the place we click, who should be given this time, which is why there is an event distribution.

Let's take a look at the tree structure of the view first:

The above two extra stuff is phonewindowand decorviewwhere the color theme and title bar content is mainly responsible for decorview display, that PhoneWindowis to do what?

PhoneWindowIt is inherited windowand is the windowonly implementation class. It windowis an abstract class and the top-level container of all views. The appearance and behavior of the views are under his control. Whether it is background display, title bar or event handling, it is his management category. It In fact, it's like the overlord of the View world.

DecorViewIs PhoneWindowan inner class, his position is equivalent to a small eunuch, is followed PhoneWindowaround professional PhoneWindowservices, in addition to his own work, is also responsible for passing messages, PhoneWindowinstructions by DecorViewinformation passed to below View, and View of the following also passed DecorViewback toPhoneWindow

Event distribution, interception, consumption

Types of Related methods Activity ViewGroup View
Event distribution dispatchTouchEvent
Event interception onInterceptTouchEvent X X
Event consumption onTouchEvent

Activity, as the original event dispatcher, does not need to intercept the event, if the event needs to be undistributed, it is fine.

Similarly, the view does not need to intercept the event at the end of the event transmission, and it does not need to process the return.

The event is first passed to the Activity after being collected, and then passed down in turn:

Activity -> PhoneWindow -> DectorView -> ViewGroup -> ... -> view

If no View consumes the event, then the event will be passed back in the opposite direction, and finally passed back to the Activity. If the activity is not processed at the end, this event will be discarded:

Activity <- PhoneWindow <- DecorView <- ViewGroup <- ... <- View

The above model is a very classic chain of responsibility model

8. Talk about the drawing process of View from the start of the app to the display on the interface

In the attach method of the activity, a PhoneWindow is created.

Calling setContentView in onCreate setContentViewis windowan abstract method. The real implementation class is PhoneWindow:

 @Override
    public void setContentView(int layoutResID) {
        if (mContentParent == null) {

//1.初始化
        //创建DecorView对象和mContentParent对象 ,并将mContentParent关联到DecorView上
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();//Activity转场动画相关
        }

//2.填充Layout
        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);//Activity转场动画相关
        } else {
        //将Activity设置的布局文件,加载到mContentParent中
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }

        //让DecorView的内容区域延伸到systemUi下方,防止在扩展时被覆盖,达到全屏、沉浸等不同体验效果。
        mContentParent.requestApplyInsets();

//3\. 通知Activity布局改变
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {

        //触发Activity的onContentChanged方法  
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

There are two core methods: installDecor() and mLayoutInflater.inflate(layoutResID, mContentParent);

installDecor will create an DecorViewobject that will serve as the root view of the entire application window. Then configure different window decoration attributes (style theme, etc.).

mLayoutInflater.inflate is to parse xml, depth-first recursive parse xml, layer by layer added to the root view, and finally return to the root view. The parsing part roughly contains two points:

1. Resolve the View object
. 2. Resolve the Params corresponding to the View and set it to the View.

9. Do you know what causes ANR and how to avoid it

There are four situations that can cause ANR to occur:

  1. Cannot respond to screen touch events or keyboard output within 5 seconds
  2. When the onReceive()function broadcast in the foreground is executed , the processing is not completed in 10 seconds, and the background is 20 seconds
  3. The foreground service is within 20 seconds, and the background service is not executed within 200 seconds.
  4. ContentProviderThe publishnot be finished in the 10s

How to avoid:

Try to avoid doing time-consuming operations in the main thread. Multithreading ==> leads to how to achieve multithreading, the use of thread pool

How to analyze ANR:

  1. After generating anr, data/anr/a file will be generated in the directorytraces.txt
  2. LogcatView in
  3. Java thread call analysis
  4. DDMS analysis

10. Have you done app performance optimization?

  1. App startup acceleration: The startup of an app is divided into three different states, among which, we only need to optimize the first state. For the App, the startup timeline we can control is nothing more Application的onCreatethan the rendering of the first screen Activity.

    1. Cold start: The App has not been started or the App process has been killed, and the App process does not exist in the system. At this time, the start of the App needs to create the App process, load related resources, start the main thread, initialize the first screen Activity, etc.
    2. Hot start: App process is only in the background, and the system just brings it from the background to the foreground and shows it to the user. The screen will display a blank window (color based on the theme) until the activity is rendered.
    3. Warm start: between cold start and hot start, generally occurs in the following two situations,
      1. The user back exits the App, and then starts it again. The App process may still be running, but the activity needs to be rebuilt
      2. After the user exits the App, the system may kill the App due to memory reasons, and the process and activity need to be restarted, but the saved instance state of the passive kill lock can be restored in onCreate
  2. Layout optimization reduces unnecessary nesting

    1. Try not to nest RelativeLayout
    2. Try not to use the weight attribute in nested LinearLayout
    3. ConstraintLayout
    4. Make good use of TextView's Drawable to reduce the layout level
  3. Response optimization

  4. Memory optimization of the use of bitmap, jusdecodeBounds property of options, set only the width and height of the bitmap to be parsed, and then use insimplesize to compress the bitmap. In the era of android2.3, the recycling of bitmap needs to call the recycler method and make it empty, but after that, only the emptying operation is required.

    Load a big picture: use BitmapRegionDecode for partial decoding

    • decodeRegion(Rect rect, BitmapFactory.Options options) Specify the rect area to get the image, the options parameter does not support inPurgeable, all others are supported

    Implementation of lru algorithm => LinkedHashMap

  5. Battery usage optimization

  6. Network Optimization

At last

Due to the length of the article, it is not possible to fully display the common knowledge points of Android interviews. In order to help everyone to learn from them, the editor has organized the Android interview knowledge points in PDF document form, and uploaded the CSDN development platform codechina address: https ://codechina.csdn.net/u012165769/Android-T3 for your reference and learning.

The Android interview knowledge points are organized in the form of PDF documents and uploaded to the CSDN development platform codechina address: https://codechina.csdn.net/u012165769/Android-T3 for your reference and learning.

Guess you like

Origin blog.csdn.net/u012165769/article/details/115016514