Common source code for Android interview questions (two): OkHttp, Retrofit, custom View source code analysis summary

In a responsible attitude towards the interview, record all the knowledge points in the interview process, not the introductory series, if you don’t understand, learn by yourself.

At present, the following aspects are summarized:

  • Android optimization
  • HashMap analysis
  • Handler source code analysis
  • OkHttp analysis
  • Retrofit analysis
  • Custom View

Due to space reasons, it is divided into two parts to share. The previous article explained the first three aspects, and today I will talk about the remaining three parts, and the following will continue to be updated.

OkHttp analysis

Okhttp is a package for Socket. There are three main classes, Request, Response, and Call by default using new OkHttpClient() to create the initial client object.

If you need to initialize the parameters of the network request, such as timeout, interceptor, etc., you can create a Builder, and create the initial client object through builder.build().

Use new Request.Builder().url().builder() to create the initial requst object.

Create a call object through client.newCall(), use call.excute() synchronously, call, enqueue() asynchronously. Here Call is an interface, and the specific implementation is in the RealCall implementation class.

The efficiency of Okhttp is reflected in the Dispatcher class in okhttp, which is a thread pool maintained internally by okhttp, which initially defines the maximum number of connections and the maximum number of host visits. Maintain 3 queues and 1 thread pool

readyAsyncCalls

The pending access request queue, which stores the requests to be executed.

runningAsyncCalls

Asynchronous request queue, which stores the ongoing execution, including the cancelled but not yet finished requests.

runningSyncCalls

Synchronous request queue, the request being executed, including the request that has been cancelled but not yet finished.

ExecutorService

Thread pool, minimum 0, maximum Max thread pool

When calling.excute() is executed, the excute method in the realcall class is called. This is a synchronous method. The first line of the method is locked and the executed flag is judged. If it is true, an exception is thrown to ensure a request Only executed once. If false, continue downward execution. Call client.dispatcher.excute() to enter the dispatcher class and add the current request to the runningSyncCalls queue. The finished method will be called at the end of execution

If it is an asynchronous operation, a RealCall.AsyncCall object will be created, the NamedRunnable interface inherited by AsyncCall , and NamedRunnable is a runnable. Into the enqueue() method of Dispatcher, first judge the thread data in the thread pool and the host's access amount. If none of them reach, then add it to runningAsyncCalls and execute it. Otherwise, it is added to the readyAsyncCalls queue.
Finished method, if it is an asynchronous operation, promoteCall method, use iterator to traverse readyAsyncCalls in promoteCalls() and then add it to runningAsyncCalls

RealConnection

The real connection operation class, soket package, http1/http2 selection, ssl protocol and so on. A recalconnection is a link

ConnectionPool

The link pool manages http1/http2 connections. The same address shares a connection to realize link reuse.

StreamAlloction

Saved link information, address, HttpCodec, realconnection, connectionpool and other information

Create and start the interceptor chain in getResponseWithInterceptorChain() in realCall

The interceptors in Okhttp are divided into 5 types by default

  • RetryAndFollowUpInterceptor
    does network failure reconnection, but not all requests need to be reconnected, according to the response code. MAX_FOLLOW_UPS=20 Maximum number
    of reconnections Create a StreamAllocation object in the intercept method and call the chain.proceed method to execute the next interceptor, process the request, and return the response.
  • BirdgeInterceptor
    initialization information, add request headers , such as gzip, keep-alive, and decompress the returned response

  • There are Cache classes inside CacheInterceptor , which handle caching operations, intercache internal classes, disklrucache algorithm, etc. The
    focus is not to cache non-get requests.
    CacheStrategy cache strategy class, obtained through factory mode
  • ConnectionInterceptor ( recommended to focus on reading the source code )
    establish a link, use the previously created StreamAllocation, initialize httpcodec, realConnection. Internal use similar gc mark cleaning algorithm to mark useless connections, StramAlloction gradually becomes 0, thread pool detection and recycling, to ensure multiple healthy keep-alive links
  • CallServerInterceptor
    initiates a real network request, parses the returned data
    http and writes it to the network IO stream, and reads the data returned to the client from the network IO stream.
  • Network Interceptors
    Application interceptors & Network Interceptors difference view related information
    okhttp wiki

Design patterns in OkHttp

Singleton, Builder, Strategy, Chain of Responsibility, Observer

Thinking:
the difference between strategy and simple factory

Related interview questions:

  1. Chain of Responsibility Model DEMO
  2. IO operation process
  3. Let's talk about the three-level cache process
  4. What are the methods to request configuration.
  5. What is the saving of okhttp resumable transmission and how to realize the resumable transmission process

Retrofit analysis

Design patterns involved

Appearance mode, builder mode, factory mode, agent mode, adapter mode, strategy mode, observer mode

Generalize

Retrofit is an encapsulation of a network request framework. Okhttp, which is used by default for the underlying network request, only simplifies the parameter configuration of the user's network request. It can also be combined with Rxjava to make it more simple and convenient to use.

  • The App application requests the network through Retrofit, which actually uses the Retrofit interface layer to encapsulate the request parameters, and then OkHttp completes the subsequent request operations.
  • After the server returns the data, OkHttp delivers the original results to Retrofit, and Retrofit parses the results according to the user's needs.
  • Complete data conversion (converterFactory), adaptation (callAdapterFactory), and various extensions through design patterns.

use

    @GET("/user/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);

    //call封装了整个okhttp的请求

    Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("https://api.github.com/")
                        .addConverterFactory(GsonConverteractory.create())
                        //.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build();
    //converterFactory
    //后续交个okhttp

Seven steps to use Retrofit

  • Add Retrofit dependency, network permissions
  • Define the Bean that receives the data returned by the server
  • Create an interface for network requests, using annotations (dynamic proxy, core)
  • The builder mode creates Retrofit instances, converters, calladapter...
  • Create an interface instance and call specific network requests
  • call synchronous/asynchronous network request
  • Process the data returned by the server

Retrofit network communication eight steps

  1. Create Retrofit instance
  2. Define the network request interface and add annotations to the methods in the interface
  3. Generate network request objects through dynamic proxy
  4. Adapt the network request object to the platform through the network request adapter
  5. Send a network request (call) through the network request executor
  6. Parse data through data parser
  7. Switch thread through callback executor
  8. The user processes the returned result on the main thread

proxy

Provide a proxy for other objects to control access to this object

  1. Static

  2. dynamic

    • Agent mode created when the program is running
    • Non-invasive enhancement
    • jdk dynamic proxy vs cglib

jdk dynamic proxy

  • Only for interface dynamics
  • InvocationHandler must be implemented
  • Get parameters from invoke parameters
  • The return value of invoke is returned to the user
  • InvocationHandler is passed in newProxyInstance

to sum up:

  1. Runtime
  2. InvocationHandler interface and Proxy class
  3. The difference between dynamic proxy and static proxy

Source code

  1. serviceMethonCache //Cache, network request object
  2. Factory callFactory //default ok
  3. HttpUrl baseUrl
  4. List<Converter.Factory> converterFactories
  5. List<CallAdapter.Factory> callAdapterFactories
  6. Executor callbackExecutor //Execute callback
  7. boolean validateEagerly //Whether to parse the method in the interface immediately

builder

  1. platform

Singleton get
MainthreadExecutor in different platforms Android platform

callAdapterFactory

Encapsulate the original Call through calladapter to find the corresponding actuator. For example, the Observable corresponding to rxjavaCallFactory, the conversion form Call<T> --> Observable<T>

converterFactory

The data analysis Converter converts the response into the corresponding data format, GsonConverterFactory, FastJsonConverterFactory through the converterFactory.

Retrofit

The Retrofit core class, which provides external interfaces. Create retrofit instance and appearance mode through retrofit.create(). In the create() method, the dynamic proxy mode is used to encapsulate the method in the requested interface (ServiceMethod), and OkhttpCall is initialized.

ServiceMethod

The core processing class, analysis method and annotation, HttpRequest is generated in the toRequest() method. Create responseConverter (convert the response stream to String or entity), create callAdapter

OkhttpCall

It is a package call to okhttp3.Call

Custom View

Three ways to customize View, combine existing controls, inherit existing controls, and inherit View

This article only focuses on the way of inheriting View, the other two learn by themselves.

1. Rewrite method

onMeasure、 onLayout、onDraw、onTouchEvent

onMeasure

It may be triggered multiple times. Pay attention to MeasureSpec during the measurement process. SpecMode and specSize
talk about LinearLayout and RelativeLayout source code.

MeasureSpec

MeasureSpec,specMode、specSize

  1. EXACTLY

Indicates that the parent layout hopes that the size of the child layout should be determined by the value of specSize. The system will set the size of the child layout according to this rule by default. Of course, developers can also set it to any size according to their wishes.

  1. AT_MOST

Indicates that the sub-layout can only be at most the size specified in specSize. Developers should set this layout as small as possible and ensure that it does not exceed specSize. By default, the system will set the size of the sub-layout according to this rule. Of course, developers can also set it to any size according to their wishes.

  1. UNSPECIFIED

Means that developers can set the layout to any size according to their wishes, without any restrictions. This kind of situation is relatively rare, and it is rarely used.

childParams/parentMode EXACTLY AT_MOST UNSPECIFIED
dp/px EXACTLY(childsize) EXACTLY(childsize) EXACTLY(childsize)
match_parent EXACTLY(parentsize) AT_MOST(parentsize) UNSPECIFIED(0)
wrap_content AT_MOST(parentsize) AT_MOST(parentsize) UNSPECIFIED(0)

The above chart is taken from https://blog.csdn.net/singwhatiwanna/article/details/38426471

onLayout

In the ViewGroup, it is triggered only once to determine the position of the child View

onDraw

Draw content, Canvas.drawxxx(), paint

onTouchEvent

Handling click events

2. The difference between custom view and viewgroup

  1. onDraw(Canvas canvas)

The method used for redrawing in the View class. This method is a method that all View, ViewGroup and their derived classes have, and it is also the most important method for Android UI drawing. Developers can override this method, and draw their own graphics and image effects based on the parameter canvas inside the overloaded method.

  1. onLayout()

Overloading this class can be customized when the layout changes, which is very useful when implementing some special effects. OnLayout in View does not have to be rewritten, onLayout() in ViewGroup is abstract, and custom ViewGroup must be rewritten.

  1. dispatchDraw()

The ViewGroup class and its derived classes have methods that control the drawing and distribution of sub-Views. Overloading this method can change the drawing of sub-Views, and then realize some complex visual effects. For typical examples, see the dispatchDraw overload of the Workspace of the Launcher module.

  1. drawChild()

The ViewGroup class and its derived classes have methods that directly control the drawing of a specific sub-view of a certain bureau, and overload this method to control a specific sub-view.

3. View method execution process

Three measures, two layouts and one draw
http://blog.csdn.net/u012422440/article/details/52972825

The root node of the Android view tree is DecorView, which is a subclass of FrameLayout, so its subviews will be drawn twice, so the onMeasure function will be called twice first.

  • onResume(Activity)
  • onPostResume(Activity)
  • onAttachedToWindow(View)
  • onMeasure(View)
  • onMeasure(View)
  • onLayout(View)
  • onSizeChanged(View)
  • onMeasure(View)
  • onLayout(View)
  • onDraw(View)
  • dispatchDraw()

4. invalidate()、postInvalidate()、requestLayout()

invalidate()

/**
     * Invalidate the whole view. If the view is visible,
     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
     * the future.
     * <p>
     * This must be called from a UI thread. To call from a non-UI thread, call
     */
    public void invalidate() {
        invalidate(true);
    }

The invalidate method will execute the draw process and redraw the View tree.
When changing the visibility, background, state (focus/enable) of the view, etc., these all belong to the category of appearance and will cause the invalidate operation. Need to update the interface display, you can directly call the invalidate method.

note:

View (non-container class) call invalidate method will only redraw itself, ViewGroup call will redraw the entire View tree.

postInvalidate()

/**
     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
     * Use this to invalidate the View from a non-UI thread.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     */
    public void postInvalidate() {
        postInvalidateDelayed(0);
    }

Called in the child thread to refresh the UI.

requestLayout()

 /**
     * Call this when something has changed which has invalidated the
     * layout of this view. This will schedule a layout pass of the view
     * tree. This should not be called while the view hierarchy is currently in a layout
     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
     * end of the current layout pass (and then layout will run again) or after the current
     * frame is drawn and the next layout occurs.
     *
     * <p>Subclasses which override this method should call the superclass method to
     * handle possible request-during-layout errors correctly.</p>
     */
    @CallSuper
    public void requestLayout() {
        }

When the width and height of the View have changed and it no longer fits in the current area, call the requestLayout method to re-lay out the View.
When the View executes the requestLayout method, it will recurse upwards to the top-level parent View, and then execute the requestLayout of this top-level parent View, so the onMeasure and onLayout of other views may also be called.

Review route of interview with big factory

I won’t talk about the extra words. Next, I will share a review route for the interview. If you are also preparing for an interview but do not know how to review efficiently, you can refer to my review route. If you have any questions, please feel free to communicate with each other. Come on!

Here is a direction for everyone to learn systematically:

1. Watch the video for systematic learning

The experience of Crud in the past few years has made me realize that I am really a fighter in the rookie. It is also because of Crud that my technology is relatively fragmented and not deep enough to be systematic, so it is necessary to study again. What I lack is system knowledge, poor structural framework and ideas, so learning through videos is better and more comprehensive. Regarding video learning, individuals can recommend to study at station B. There are many learning videos on station B. The only drawback is that they are free and easily outdated.

In addition, I have collected several sets of videos myself, and I can share them with you if necessary.

2. To systematically sort out knowledge and improve reserves

There are so many knowledge points in client development, and there are still so little things in the interview. Therefore, there are no other tricks for the interview, just to see how well you prepare for these knowledge points. So, when you go out for an interview, it is good to see which stage you have reached in your review.

System learning direction:

  • Essential skills for architects: in-depth Java generics + annotations in simple language + concurrent programming + data transmission and serialization + Java virtual machine principle + reflection and class loading + dynamic proxy + efficient IO

  • Android advanced UI and FrameWork source code: advanced UI promotion + Framework kernel analysis + Android component kernel + data persistence

  • 360° overall performance tuning: design ideas and code quality optimization + program performance optimization + development efficiency optimization

  • Interpretation of open source framework design ideas: hot repair design + plug-in framework interpretation + component framework design + image loading framework + network access framework design + RXJava responsive programming framework design + IOC architecture design + Android architecture component Jetpack

  • NDK module development: NDK basic knowledge system + underlying image processing + audio and video development

  • WeChat Mini Program: Mini Program Introduction + UI Development + API Operation + WeChat Docking

  • Hybrid development and Flutter: Html5 project combat + Flutter advanced

After the knowledge is sorted out, it is necessary to check and fill in the vacancies. Therefore, for these knowledge points, I have prepared a lot of e-books and notes on hand. These notes provide a perfect summary of each knowledge point.

3. Read the source code, read the actual combat notes, and learn the ideas of God

"Programming language is the way the programmer expresses, and the architecture is the programmer's perception of the world." Therefore, if programmers want to quickly understand and learn the architecture, reading the source code is essential. Reading the source code is to solve problems + understand things, and more importantly: see the ideas behind the source code; programmers say: read thousands of lines of source code, and practice thousands of ways.

Mainly include WeChat MMKV source code, AsyncTask source code, Volley source code, Retrofit source code, OkHttp source code, etc.

4. On the eve of the interview, sprint questions

Within a week before the interview, you can start sprinting. Please keep in mind that when brushing the questions, the technology is the first priority, and the algorithm is basic, such as sorting, etc., and the intellectual questions are generally not asked unless they are school recruits.

Regarding the interview questions, I personally prepared a set of systematic interview questions to help you learn from one another:

to sum up

There is no shortcut to change your life. You need to walk this path yourself. Only deep thinking, constant reflection and summary, maintaining the enthusiasm for learning, and building your own complete knowledge system step by step are the ultimate ways to win. It is also the mission that programmers should undertake.

The above content is free to share with everyone, friends who need the full version, click here to see all the content .

Guess you like

Origin blog.csdn.net/weixin_44339238/article/details/112616741