Although I no longer work on Android, I still pay close attention to Android. Here is a summary of the Android interview in 2018 according to the information on the Internet.

1. Activity lifecycle? OnCreate () -> onStart() -> onResume() -> onPause() -> onStop() -> onDetroy()

2. Service life cycle?

There are two ways to start a service: startService() and bindService(). Different startup modes have different life cycles.

StartService () calls startService() –> onCreate()–> onStartConmon()–> onDestroy(). This way to start, need to pay attention to a few problems, first: When we call startService,onCreate() will only be called once, and onStartConmon() will be called multiple times. When we call stopService(), OnDestroy () is called to destroy the service. OnStartConmon () : if the intent is null, the intent is null. If the intent is null, the intent is null.

BindService () is used to bind a service. BindService –>onCreate()–>onBind()–>unBind()–>onDestroy() bingService For example, there are several methods to add to a service. If you want to call them in an activity, you need to get the ServiceConnection object in the activity, and use ServiceConnection to get the class object in the service. This class object is then used to call methods in the class, which of course inherits from the Binder object.

3. Start the Activity

There are two ways to start an app. The first way is to click the corresponding application icon on the desktop launcher, and the second way is to start a new activity by calling startActivity in the activity.

When we create a new project, the default root activity is the MainActivity, and all activities are stored on the stack, so when we start a new activity, we put it on top of the previous activity, and when we click the application icon from the desktop, Since the launcher itself is an application, when you click on the icon, the system calls startActivitySately(). Typically, information about the activity you start is stored in the intent, such as action, category, and so on.

When we install this application, the system will also start a management service of PackaManagerService. This management service will parse the androidmanifest. XML file to get relevant information in the application, such as service, activity, Broadcast, etc., and then get information about the relevant components. When we click on the application icon, the startActivitySately() method is called, Inside the method, startActivty() is called, and the startActivity() method eventually calls the startActivityForResult() method. The startActivityForResult() method. Since the startActivityForResult() method returns a result, the system simply gives a -1 to indicate that the result is not needed.

The startActivityForResult() method actually starts the activity with the execStartActivity() method in the Instrumentation class, The Instrumentation class is mainly used to monitor the interaction between the program and the system. In the execStartActivity() method, you get a proxy object for ActivityManagerService from which to start the activity. The startup will call a checkStartActivityResult() method that will throw an exception if the component is not configured in the configuration manifest.

Finally, of course, is to call Application. ScheduleLaunchActivity () to start the activity, and this method by getting a ActivityClientRecord object, The ActivityClientRecord uses a handler to send messages. Each activity component is described using an ActivityClientRecord object. The ActivityClientRecord object holds a LoaderApk object that starts the Activity component by calling the handleLaunchActivity, from which the page lifecycle methods are called.

4. Broadcast registration mode and differences? When to use dynamic registration?

Broadcast Broadcast. There are two registration modes.

The first is static registration, which can also be a resident broadcast, which needs to be registered in androidmanifest.xml, and the broadcast registered in this way is not affected by the page life cycle, even if you exit the page, you can receive the broadcast which is usually used when you want to boot up and so on, Since this registered broadcast is a resident broadcast, it consumes CPU resources.

The second one is dynamic registration, and dynamic registration, when you register in code, is also called non-resident broadcasting, because when you get a life cycle effect, when you exit the page, you don’t get a broadcast, and we usually use that for UI updates. This registration mode has a higher priority. Finally, you need to unbind it to avoid memory leakage

Broadcasting is divided into orderly broadcasting and disordered broadcasting.

HttpClient and HttpUrlConnection

Which request method is used in Volley (HttpClient before 2.3, HttpUrlConnection after 2.3)

HttpClient and HttpUrlConnection both support Https. They upload or download data in the form of streams, or transfer data in the form of streams. They also support ipv6 and connection pooling. HttpClient has so many apis that it is difficult to extend it without breaking its compatibility, which is why Google scrapped it for Android6.0.

HttpUrlConnection is relatively lightweight, with fewer apis, easy to expand, and can meet most of the Android data transfer. Volley, a classic framework, used HttpClient until version 2.3 and HttpUrlConnection since.

6. Differences between Java virtual Machine and Dalvik Virtual Machine

Java Virtual machine:

1. Java virtual machines are stack based. Stack-based machines must use instructions to load and manipulate data on the stack, and many more instructions are required.

2. Java virtual machines run Java bytecode. (Java classes are compiled into one or more bytecode.class files.)

Dalvik virtual machine:

1. Dalvik virtual machine is register-based

2. Dalvik runs a custom. Dex bytecode format. After the Java class is compiled into a.class file, a dx tool converts all the.class files into a.dex file from which the Dalvik virtual machine reads instructions and data

Constant pools have been modified to use only 32-bit indexes to simplify the interpreter.

4, one application, one virtual machine instance, one process (All Android application threads are corresponding to a Linux thread, all run in their own sandbox, different applications run in different processes. Each Android Dalvik application is given a separate Linux PID(APP_ *).

7, how the system process to survive (undead process)

Extending here: What is the priority of the process

The current industry of Android process survival means are mainly divided into black, white, gray ** three, its general implementation ideas are as follows:

Black: Different APP processes wake up each other with broadcasts (including system-provided broadcasts)

White: Start foreground Service

Grey Protection: Start foreground Service using system vulnerability

Black keep alive

The so-called black survival is the use of different APP processes using broadcast to wake up each other. Here are three common scenarios:

Scenario 1: Wake up the APP with the broadcast generated by the system during startup, network switching, photo taking, and video shooting

Scenario 2: Accessing a third-party SDK will also wake up the corresponding APP process. For example, the wechat SDK will wake up wechat, and the Alipay SDK will wake up Alipay. Spreading out from this will directly trigger scenario 3 below

Scenario 3: If you have Alipay, Taobao, Tmall, UC and other Alibaba apps installed in your mobile phone, you may wake up other Alibaba apps after opening any of them. (Just take Ali as an example, in fact, BAT is similar)

White keep alive

The white preservation method is very simple. It is to call the system API to start a foreground Service process, which will generate a Notification in the Notification bar of the system to let users know that such an app is running, even if the current APP has retreated to the background. LBE and QQ Music are as follows:

Gray keep alive

Gray preservation, this means of preservation is the most widely used. It takes advantage of system vulnerabilities to start a foreground Service process. The difference with the common startup mode is that it does not show a Notification in the system Notification bar, and looks like running a background Service process. The advantage of this is that the user will not know that you are running a foreground process (because the Notification cannot be seen), but your process has a higher priority than a normal background process. Then how to use the system vulnerabilities, the general implementation ideas and codes are as follows:

New Notification() is passed to the foreground Service when API < 18.

API >= 18 start two foreground services with the same ID, and then stop the last Service

If you are familiar with the Android system, you will know that the system does not actually kill the process when the app goes back to the background, but cache it for the sake of experience and performance. The more applications open, the more processes are cached in the background. When the system memory is insufficient, the system starts to determine which processes to kill according to its own process reclaiming mechanism, so as to free up memory for the needed app. This mechanism is called Low Memory Killer, which is based on OOM Killer (out-of-memory Killer) mechanism Of Linux kernel.

The importance of the process, divided into 5 levels:

Foreground Process

Visible Process

Service Process

Background Processes

Empty Processes

Low Memory Killer Low Memory Killer What is oom_adj? It is a value assigned by the Linux kernel to each system process. It represents the priority of the process, and the process reclamation mechanism determines whether to recycle based on this priority. Here’s what you need to remember about what oOM_adj does:

The larger the oOM_adj value is, the lower the priority is and the easier the process is to be killed and reclaimed. The smaller the value is, the higher the process priority is and the harder it is to kill and recycle

If the oOM_adj of a common APP process is 0, the oOM_adj of a system process can be <0

Some phone manufacturers have whitelisted these well-known apps to improve user experience by keeping the process immortal (wechat, QQ and Momo are all on Xiaomi’s whitelist). If they are removed from the whitelist, they will eventually be killed just like ordinary apps. In order to avoid being killed, it is better to do a good job of optimization.

Therefore, the fundamental solution to process survival comes back to performance optimization after all, and process immortality is a completely false proposition after all!

8. Explain the Context

Context is an abstract base class. In the context of translation, it can also be understood as the environment, which provides basic information about the running environment of some programs. Context has two subclasses, ContextWrapper, which encapsulates the Context functionality, and ContextImpl, which implements the Context functionality. ContextWrapper has three direct subclasses, ContextThemeWrapper, Service, and Application. ContextThemeWrapper is a wrapper class with a theme, and it has a direct subclass Activity. Therefore, the Context of an Activity is different from that of a Service or Application. Only an Activity needs a theme. A Service does not require a theme.

Context is of three types: Application, Activity, and Service. These three classes have different functions, but they are all part of the Context, and their Context functions are implemented by the ContextImpl class. Therefore, in most scenarios, The three types of Context, Activity, Service, and Application, are all generic. However, there are a few special scenarios, such as starting an Activity and popping up a Dialog. For security reasons, Android does not allow an Activity or Dialog to appear out of thin air, and one Activity must be launched on top of another, creating a return stack. A Dialog must pop up on top of an Activity (unless it’s a System Alert Dialog), so in this scenario we can only use an Activity-type Context, otherwise we’ll get an error.

The getApplicationContext() and getApplication() methods return the same application object, but of different types.

Number of contexts = Number of Activities + Number of Services + 1 (1 is Application)

9. Understand the relationship between Activity, View and Window

That’s a really hard question to answer. So here’s a good analogy to describe their relationship. An Activity is like a craftsman (a control unit), a Window is like a Window (a carrying model), a View is like a Window splint (a display View), layoutInflaters are like scissors, and Xml configurations are like a Window splint.

1: Activity construction initializes a Window, specifically a PhoneWindow.

2: This PhoneWindow has a “ViewRoot”, which is a View or ViewGroup, which is the original root View.

3: “ViewRoot” through the addView method to add views one by one. TextView, Button, etc

WindowManagerService receives the message and calls back the Activity function. Such as onClickListener, onKeyDown, etc.

10. Four LaunchModes and their usage scenarios

Extended here: the difference between stack (First In Last Out) and queue (First In First Out)

Stack vs. queue:

  1. Queue first in first out, stack first in last out

  2. “Qualification” for insert and delete operations. A stack is a linear table that limits insert and delete operations to one end of the table. A queue is a linear table that is limited to inserting at one end of the table and deleting at the other.

  3. Traverse data at different speeds

Standard model

This is the default mode, and every time an Activity is activated, an instance of the Activity is created and added to the task stack. Usage scenario: Most Activities.

SingleTop mode

If an instance of the Activity happens to exist at the top of the task’s stack, it is reused (its onNewIntent() is called), otherwise a new instance is created and placed at the top of the stack, even if an instance of the Activity already exists, as long as it is not at the top of the stack. Use scenarios such as content pages of news or reading apps.

SingleTask mode

If you already have an instance of the Activity on the stack, reuse it (calling its onNewIntent()). When reused, the instance is pushed back to the top of the stack, so instances above it are moved off the stack. If the instance does not exist on the stack, a new instance will be created and added to the stack. Use scenarios such as the main page of the browser. No matter how many apps you launch the browser from, it only launches the home screen once, otherwise it goes to onNewIntent and clears the other pages above the home screen.

SingleInstance mode

Create an instance of the Activity in a new stack and share it with multiple applications on that stack. Once an Activity instance of this pattern already exists in a stack, any application that activates the Activity reuses the instance in that stack (calling the instance’s onNewIntent()). The effect is similar to multiple applications sharing an application, and whoever activates the Activity will enter the same application. Usage scenario For example, separate the alarm setting from the alarm setting. A -> B (singleInstance) -> C (A -> B (singleInstance) -> C)

11. Briefly describe the drawing process of View

Custom controls:

1, combination control. This custom control does not require us to draw, but uses native control composition of new controls. Like the title bar.

2, inherit the original control. This custom control can add its own methods in addition to those provided by native controls. For example, make rounded corners and round pictures.

3. Fully custom controls: All the content displayed on this View is drawn by ourselves. Like making a water ripple progress bar.

OnMeasure() — >OnLayout() — >OnDraw()

Step 1: OnMeasure() : Measures the view size. The measure method is recursively called from the top-level parent View to the child View, and the measure method calls back to the OnMeasure.

Step 2: OnLayout() : Determine the position of the View and carry out the page layout. The process of recursively calling the view.layout method from the top-level parent View to the child View, that is, the parent View puts the child View in the appropriate position according to the layout size and layout parameters obtained by measure child View in the previous step.

Step 3: OnDraw() : Draw the view. ViewRoot creates a Canvas object and calls OnDraw(). Six steps: 1. Draw the background of the view; ② save the Layer of the canvas; ③ Draw the content of the View; (4) Draw a sub-view of the View, if there is no use;

⑤, restore Layer; ⑥ draw the scroll bar.

View, ViewGroup event distribution

  1. There are only two protagonists in Touch event distribution :ViewGroup and View. A ViewGroup contains onInterceptTouchEvent, dispatchTouchEvent, and onTouchEvent. View contains two related events: dispatchTouchEvent and onTouchEvent. The ViewGroup inherits from the View.

2. The ViewGroup and View form a tree structure, and the root node is a ViwGroup contained within the Activity.

3. Touch events are composed of Action_Down, Action_Move and Aciton_UP. In a complete touch event, there is only one Down and one Up, and several Move events can be 0.

4. When Acitivty receives Touch events, it will traverse the sub-view to distribute Down events. ViewGroup traversal can be considered recursive. The purpose of the distribution is to find the View that actually handles the full touch event, which will return true on the onTouchuEvent result.

5. When a child View returns true, the distribution of Down events is aborted and the child View is recorded in the ViewGroup. Subsequent Move and Up events are handled directly by the child View. Since the sub-view is stored in the ViewGroup, when the node structure of the multi-layer ViewGroup is saved, the upper ViewGroup will save the ViewGroup object where the View that handles the event is: for example, in the structure of viewGroup0-viewGroup1-textView, TextView returns true, it’s going to be stored in ViewGroup1, and ViewGroup1 is going to return true, it’s going to be stored in ViewGroup0. When Move and UP events come, they are passed from ViewGroup0 to ViewGroup1, and from ViewGroup1 to TextView.

6. When no child View in a ViewGroup captures a Down event, the onTouch event of the ViewGroup itself is emitted. This is triggered by calling the super.DispatchTouchEvent function, the dispatchTouchEvent method of the parent View class. The onTouchEvent method of the Acitivity is triggered when none of the child views are processed.

OnInterceptTouchEvent has two functions: 1. Intercept the distribution of Down events. 2. Abort the transfer of Up and Move events to the target View, so that the ViewGroup where the target View resides captures Up and Move events.

13. Save the Activity state

OnSaveInstanceState (Bundle) is called before the activity goes into the background state, that is, before onStop() and after onPause.

14. Several animations in Android

Frame animation: by specifying the picture and playing time of each frame, the animation effect is formed by orderly playing, such as the rhythm bar you want to hear.

Tween animation: by specifying the initial state, change time and method of View, a series of algorithms are used to transform graphics to form animation effects, mainly including Alpha, Scale, Translate and Rotate. Note: This animation is only implemented in the View layer, without really changing View properties, such as sliding lists and changing the transparency of the title bar.

Property animation: only supported on Android3.0, you can animate the View by constantly changing its properties and constantly redrawing it. The properties of the View are really changed compared to the View animation. For example, view rotation, zoom in, zoom out.

Intents, ContentProviders, broadcasts, services, and sockets can communicate with each other across processes.

Intent: This cross-process approach is not in the form of accessing memory; it requires passing a URI, such as making a phone call.

ContentProvider: This form uses the form of data sharing to share data.

Service: remote service, aidl

radio

16. AIDL understands and briefly describes Binder mechanisms

AIDL: Each process has its own Dalvik VM instance, has its own block of independent memory, stores its own data in its own memory, performs its own operations, and spends its life in its own narrow space. Aidl is similar to a bridge between two processes, enabling data transmission between two processes. There are various options for cross-process communication, such as BroadcastReceiver, Messenger, etc., but BroadcastReceiver occupies more system resources. If it is frequent cross-process communication is obviously not desirable; The request queue for Messenger communication across processes is synchronous and cannot be executed concurrently.

Binder mechanism is simple to understand:

In the Binder mechanism of the Android system, there is a Client, Service, ServiceManager, Binder composed of driver, including the Client, the Service, the Service Manager running in user space, Binder drivers run in kernel space. Binder is the glue that binds these four components together. The core component is the Binder driver. Service Manager provides the auxiliary management function. Client and Service communicate between C/S on top of the infrastructure provided by Binder drivers and Service Manager. Binder drivers provide device files /dev/binder to interact with user controls.

Client, Service, and Service Manager communicate with Binder drivers through open and ioctl file operations. Interprocess communication between Client and Service is achieved indirectly through Binder drivers. Binder Manager is a daemon that manages services and provides clients with the ability to query Service interfaces.

17. Principle of Handler

In Android, the main thread cannot perform time-consuming operations, and the child thread cannot update the UI. So there’s a handler, and it’s all about communicating between threads.

Handler the whole process, there are mainly four objects, handler, Message, MessageQueue, stars. When the application is created, it creates a handler object in the main thread,

The handler sends the Message to MessageQueue by calling sendMessage. The Looper object calls loop() over and over again

The Message is continually fetched from the MessageQueue and handed to handler for processing. Thus realize the communication between threads.

18, Binder mechanism principle

In the Binder mechanism of the Android system, there is a Client, Service, ServiceManager, Binder composed of driver, including the Client, the Service, the Service Manager running in user space, Binder drivers run in kernel space. Binder is the glue that binds these four components together. The core component is the Binder driver. Service Manager provides the auxiliary management function. Client and Service communicate between C/S on top of the infrastructure provided by Binder drivers and Service Manager. Binder drivers provide device files /dev/binder to interact with user controls. Client, Service, and Service Manager communicate with Binder drivers through open and IOCtl file operations. Interprocess communication between Client and Service is achieved indirectly through Binder drivers. Binder Manager is a daemon that manages services and provides clients with the ability to query Service interfaces.

19. Principle of thermal repair

We know that the Java virtual machine (JVM) loads the class file, and the Android virtual machine (Dalvik/ART VM) loads the dex file.

ClassLoader has a subclass BaseDexClassLoader, and BaseDexClassLoader has an array — DexPathList, which is used to store dex files. When a BaseDexClassLoader calls the findClass method, it essentially iterates through the array of numbers,

Find the corresponding dex file, then return it directly. The solution to the hot fix was to add the new dex to the set, in front of the old dex,

So it gets pulled out first and returns.

Of course, in addition to this way, there are Instant Run and other programs, please find your own information to learn.

20. Android memory leaks and management

(1) The difference between memory overflow (OOM) and memory leak (object cannot be reclaimed).

(2) Causes of memory leaks

(3) Memory leak detection tool ——>LeakCanary

Out of memory: a program runs out of memory when it does not have enough memory space to use. For example, if you request an integer but store it for a long, you are out of memory. An overflow of memory is commonly referred to as not having enough memory.

Memory leak: after a program requests memory, it cannot release the allocated memory space. The damage caused by a memory leak can be ignored, but the accumulation of memory leak can be serious. No matter how much memory is leaked, it will be exhausted sooner or later

Causes of memory leakage:

Memory leaks caused by handlers.

Solution: If you declare Handler as a static inner class, you don’t hold a reference to the outer class SecondActivity, and its lifetime is independent of the outer class SecondActivity.

If you need a context inside the Handler, you can refer to the external class by weak reference

Memory leak caused by singleton pattern.

Context is an ApplicationContext. Since ApplicationContext has the same lifecycle as app, it will not leak memory

Memory leaks caused by static instances of non-static inner classes.

Solution: Make the inner class static to avoid memory leaks

Memory leaks caused by non-static anonymous inner classes.

Solution: Make the anonymous inner class static.

5. Memory leakage caused by unpaired use of register/unregister.

Register broadcast receivers, EventBus, etc., remember to unbind.

Memory leaks caused by resource objects not being closed.

When these resources are not available, call recycler (), close (), destroy (), recycler () or release ().

Memory leaks caused by collection objects not being cleaned up in time.

Some objects are usually loaded into the collection, and when not in use, it is important to clean up the collection so that related objects are no longer referenced.

21, Fragments communicate with fragments or activities

1. Call methods in one Fragment directly from another Fragment

2. Use the interface callback

3. Use radio

4.Fragment Calls the public method of the Activity directly

22. Android UI adaptation

Font sp, dp, match_parent, wrap_content, weight

Image resources, the resolution of different images, placed in the corresponding folder can be replaced by percentages.

23. App optimization

App optimization :(tool: Hierarchy Viewer analysis layout tool: TraceView test analysis time-consuming), APP optimization is mainly carried out from the following aspects:

App Startup optimization

Layout optimization

Response optimization

Memory optimization

Optimization of battery usage

Network optimization

App startup optimization (for cold startup)

There are three ways to launch an App:

Cold start: The App is not started or killed. The App process does not exist in the system. In this case, the App is cold start.

Hot launch: Hot launch means that your App process is just in the background, and the system just brings it from the background to the foreground and shows it to the user.

Between cold start and hot start, it generally occurs in the following two situations:

(1) The user backs out of 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 for memory reasons, and both the process and the activity need to be restarted. However, the saved instance state of the passive kill lock can be restored in onCreate.

Optimization:

The onCreate of the Application (especially the third-party SDK initialization) and the rendering of the first screen of the Activity should not be time-consuming. If there is any, it can be put into the child thread or IntentService

Layout optimization

Try not to nest too complicated. Can use,,

Response optimization

The Android system redraws our interface with the VSYNC signal every 16ms.

Reasons for page lag:

(1) overly complex layout.

(2) Complex operations of UI thread

(3) Frequent GC, frequent GC can be caused by two reasons: (1) memory jitter, that is, a large number of objects are created and released in a short time; (2) a large number of objects are created in a short time, which seriously occupies the memory area.

Memory optimization: Refer to the memory Leaks and Memory Overflow section

Optimize battery usage (use Batterystats & Bugreport)

(1) Optimize network request

(2) When using GPS in positioning, please remember to turn it off in time

Network optimization (the impact of a Network connection on a user: traffic, power, user wait) can be detected by the tool Network Monitor next to Logcat under Android Studio

API design: API design between App and Server should consider the frequency of network requests, the state of resources, etc. So that the App can fulfill the business requirements and display the interface with fewer requests.

Gzip compression: Gzip is used to compress request and Response to reduce data transmission and traffic consumption.

Image Size: the width and height of the required image can be informed to the server when obtaining the image, so that the server can provide appropriate images to avoid waste.

Network caching: Proper caching can make our application look faster and avoid unnecessary traffic consumption.

24. Image optimization

(1) Operate the picture itself. . Try not to use setImageBitmap, setImageResource, BitmapFactory decodeResource to set a larger image, because after complete the decode these methods,

This is done through createBitmap in the Java layer, which consumes more memory.

(2) The scale of the image, the SDK suggests that its value is 2 index value, the larger the value is, the picture is not clear.

(3) Use the recycle() method to recycle images.

HybridApp WebView interacts with JS

Android and JS call each other’s methods via WebView, which is actually:

Android to call JS code

  1. The loadUrl() of the WebView is simple and convenient to use. However, the efficiency is low and it is difficult to obtain the return value.

  2. EvaluateJavascript () via WebView is efficient, but is only supported for versions up to 4.4, not up to 4.4. Therefore, a mixture of the two is recommended.

JS to call Android code

  1. Through WebView addJavascriptInterface () object mapping, this method is simple to use, only the Android object and JS object mapping, but there are relatively large loopholes.

The vulnerability is caused by: when JS gets the Android object, it can call all the methods in the Android object, including the system class (java.lang.Runtime class), so as to carry out arbitrary code execution.

Solution:

(1) In Android 4.2, Google stipulated that the function to be called should be annotated with @javascriptInterface to avoid vulnerability attacks.

(2) Use intercept Prompt () to fix vulnerabilities before Android 4.2.

  1. Intercepting the URL via the WebViewClient’s shouldOverrideUrlLoading () callback. Advantages of this approach: There are no loopholes of Method 1; Disadvantages: JS gets the return value of the Android method is complicated. (Ios mostly uses this approach.)

(1)Android intercepts urls via shouldOverrideUrlLoading (), the WebViewClient callback method

(2) Protocol for parsing the URL

(3) If a pre-agreed protocol is detected, the corresponding method is called

  1. Intercept JS dialog box alert(), Confirm(), prompt () messages via WebChromeClient onJsAlert(), onJsConfirm(), onJsPrompt () callback

Advantages of this approach: There are no loopholes of Method 1; Disadvantages: JS gets the return value of the Android method is complicated.

26, Universal-Imageloader, Picasso, Fresco, Glide contrast

Fresco is an open source image caching tool from Facebook. It features two in-memory caches and a Native cache.

Advantages:

  1. Images stored in the android anonymous Shared memory, rather than the heap memory of the virtual machine, the picture in the middle of the buffer data are stored in the local heap memory, so the application has more memory use, will not lead to oom for loading images, but also reduce the garbage collector caused by frequent calls recycling Bitmap caton interface, Higher performance.

  2. Progressive loading of JPEG images, supporting images from blur to clear loading.

  3. Images can be displayed in the ImageView at any center point, not just the center of the image.

  4. JPEG image resizing is also done in Native, not in the vm heap, and also reduces OOM.

  5. Good support for GIF image display.

Disadvantages:

  1. The large frame affects the Apk volume

  2. Cumbersome to use

Universal-imageloader :(HttpClient has been abandoned by Google)

Advantages:

1. Support download progress monitoring

2. The PauseOnScrollListener interface is used to pause image loading while the View is scrolling.

3. The default implementation of a variety of memory caching algorithms can be configured for the image cache, but ImageLoader default implementation of more cache algorithms, such as Size first delete, use least first delete, least recently used, first delete, longest delete, etc..

4. Local cache file name rule definition is supported

Picasso was advantages

  1. Provides statistics monitoring function. Supports image cache usage monitoring, including cache hit ratio, used memory size, saved traffic, etc.

2. Support priority processing. Tasks with high priority will be selected before each task scheduling, for example, it is applicable when the priority of Banner in App page is higher than that of Icon.

3. Support delay until image size calculation is finished loading

4. Support flight mode and the number of concurrent threads varies according to the network type. When the mobile phone switches to flight mode or network type changes, the maximum concurrency in the thread pool will be automatically adjusted. For example, the maximum concurrency in wifi is 4,4 gb, 3,3 gb, 2. Here Picasso determines the maximum concurrency based on the network type, not the number of CPU cores.

5. None Local cache. No “local cache”, not that there is no local cache, but That Picasso didn’t implement it himself and handed it over to Square’s other web library, Okhttp, The advantage is that you can Control the expiration time of the image by requesting cache-control and Expired in the Response Header.

Glide advantages

  1. You can cache not only images but also media files. Glide is more than just an image cache, it supports GIFs, WebP, thumbnails. Even Video, so it should be used as a media cache.

  2. Support priority processing.

  3. Consistent with the Activity/Fragment life cycle, trimMemory is supported. Glide maintains a RequestManager for each context, is consistent with the Activity/Fragment life cycle through FragmentTransaction, and has a corresponding trimMemory interface implementation to call.

  4. Okhttp and Volley are supported. Glide acquires data through UrlConnection by default and can be used with okHTTP or Volley. Actual ImageLoader and Picasso also support OkHTTP and Volley.

  5. Memory friendly. Glide’s memory cache has an active design. When retrieving data from the memory cache, it uses remove instead of GET, and puts the cached data into an activeResources map with a soft reference value, and counts the references. Determine after the image is loaded, and recycle if the reference count is empty. Glide uses URL, view_width, view_height, screen resolution and other joint keys to cache processed pictures in memory instead of original pictures to save size consistent with Activity/Fragment life cycle. Support trimMemory. Images use the default RGB_565 instead of ARGB_888, which is less sharp but smaller and can also be configured to ARGB_888.

6.Glide can support URL expiration through signature or without using local caching.

Xutils, OKhttp, Volley, Retrofit

Xutils this framework is very comprehensive, can undertake network request, you can load images processing, the data can be stored, you can also view for annotations, using this framework is very convenient, but the downside is also very obvious, use the project, leads to project of this framework is very serious, once this framework appear problem, So the impact on the project is very big.

OKhttp: Android development can make web requests directly using off-the-shelf apis. Is to use HttpClient, HttpUrlConnection. Okhttp is a high performance HTTP request library for Java and Android applications. It supports synchronization and asynchronism. Okhttp also encapsulates thread pools, data conversion, parameter usage, error handling, etc. The API is much easier to use. However, we still need to make a layer of encapsulation when we use it in the project, so that it can be used more smoothly.

Volley: Volley is a set of small and smart asynchronous request library, the framework package scalability is very strong, support HttpClient, HttpUrlConnection, and even support OkHttp, Volley inside also package ImageLoader, So you don’t even need to use an image loading framework if you want to, but this feature is not as powerful as some of the specialized image loading frameworks. It can be used for simple requirements, but more complex requirements still need a specialized image loading framework. Volley also has drawbacks, such as no support for POST big data, so it’s not suitable for uploading files. But Volley itself is designed for frequent, low-volume web requests.

Retrofit: Retrofit is a Square framework for RESTful web requests wrapped in OkHttp by default. RESTful is a popular API design style, not a standard. Retrofit’s encapsulation is pretty powerful, there’s a bunch of design patterns involved, you can configure requests directly through annotations, you can use different HTTP clients, although the default is HTTP, you can serialize data using different Json Converters, and you also have support for RxJava. Using Retrofit + OkHttp + RxJava + Dagger2 is one of the most popular frameworks, but it requires a high bar.

Volley VS OkHttp

Volley’s advantage is that it encapsulates better, whereas with OkHttp you need to be able to encapsulate again. OkHttp has the advantage of higher performance, which is faster than Volley because OkHttp is based on NIO and Okio. IO and NIO both are in Java concepts, if I read from the hard disk data, the first way is the program has been, etc., the data can continue to operate after reading this is the simplest also call blocking IO, still have a kind of is you, you read the program and then to perform, such as data processing after you inform me again, and then deal with the callback. The second is NIO, which is non-blocking, so NIO is certainly better than IO, and Okio is Square’s library based on IO and NIO that is simpler and more efficient for processing data streams. In theory, Volley is more likely to use Volley than OkHttp, because Volley also supports OkHttp internally, which eliminates OkHttp’s performance advantages, and Volley itself is easier to use and more extensible.

OkHttp VS Retrofit

There is no doubt that Retrofit is encapsulation based on OkHttp by default, there is no comparison, Retrofit is definitely preferred.

Volley VS Retrofit

Both libraries are well packaged, but Retrofit decoupled more completely, especially with Retrofit2.0, where Jake rewrote a lot of the original 1.0 design misfits, more detailed responsibilities, and Retrofit uses OkHttp by default and has a performance advantage over Volley. Also, if your project uses RxJava, you should use Retrofit. So Retrofit has an advantage over the two libraries and should be used first if you can understand both frameworks. But Retrofit has a slightly higher bar than Volley, and it takes a bit of work to understand how it works, how it works, how it works, and how it works to get to the bottom ofit, and if you’re half-assed about it, it’s probably best to use Volley in commercial projects.

The Java part

1. The difference between sleep and wait in threads

(1) These two methods come from different classes. Sleep comes from Thread and wait comes from Object.

(2) The sleep method does not release the lock while the wait method releases the lock.

(3) Wait,notify, and notifyAll can only be used in synchronous control methods or synchronous control blocks, while sleep can be used anywhere.

What is the difference between the start() and run() methods in Thread

The start() method is used to start the newly created thread, and the run() method is called inside the start() method. This is not the same as calling the run() method directly. If the run() method is called directly, it is no different from ordinary methods.

3, String and StringBuffer, StringBuilder distinction

StringBuilder > StringBuffer > String (StringBuilder > StringBuffer > String)

StringBuffer is thread-safe, StringBuilder is thread-unsafe. (Because StringBuffer has buffers).

The difference between overloading and overwriting in Java

1. Overloading: A class can have multiple methods with the same name, but with different types and numbers of arguments. This is an overload.

2, overwrite: the subclass inherits the parent class, then the subclass can implement the method in the parent class, so that the new method overwrites the old method of the parent class.

5. The difference between Http and HTTPS, and the realization principle of HTTPS

1. HTTPS requires a ca to apply for a certificate. Generally, there are few free certificates, so some fees are required.

2. HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol.

3. HTTP and HTTPS use completely different connections and use different ports, the former 80 and the latter 443.

4. HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.

HTTPS implementation principle:

(1) The customer accesses the Web server using an HTTPS URL and requires an SSL connection to the Web server.

(2) After receiving the request from the client, the Web server sends a copy of the certificate information (including the public key) of the website to the client.

(3) The browser of the client and the Web server start to negotiate the security level of the SSL connection, that is, the level of information encryption.

(4) The browser of the client establishes the session key according to the security level agreed by both parties, and then encrypts the session key using the public key of the website and transmits it to the website.

(5) The Web server uses its own private key to decrypt the session key.

(6) The Web server uses the session key to encrypt the communication with the client.

6. The difference between TCP and UDP

TCP is connection-oriented and requires a three-way handshake to minimize risks and ensure connection reliability.

Udp is not connection-oriented. Before establishing a connection, UDP does not need to establish a connection with an object. So UDP is unreliable.

Real-time lines are better because UDP has lower overhead and higher transmission rates because it does not require confirmation connections.

7. Steps for establishing network connections through Socket

Establishing a Socket connection requires at least one pair of sockets, one running with the client -ClientSocket and one running with the server -ServiceSocket

1. Server monitoring: the server socket does not locate the specific client socket, but is in the state of waiting for the connection, monitoring the network status in real time, waiting for the connection request of the client.

2. Client request: the client socket makes a connection request, and the target connection is the server socket. Note: The client socket must describe the socket of the server to which it is connecting,

Indicate the address and port number of the server socket, and then make a connection request just like the server socket.

Connection confirmation: when the server socket listens to the connection request of the client socket, it responds to the request of the client socket, establishes a new thread, and puts the description of the server socket

Send to the client. Once the client confirms the description, the connection is formally established. The server socket remains in a listening state and continues to receive connection requests from other client sockets.