Maintain good mental state and good behavior habits every day

Saturday: A cup of coffee at Starbucks and an afternoon of reading (most recently Keigo Higashino’s Dawn Street) to ease monday-Friday nerves. Savor the food slowly. Watch a movie in the evening. Sunday: Stay home and watch TV all day. Go for a walk

The text start

More complete project download. To be continued. The source code. Github. You can click about me to contact me

1. Basic knowledge

Due to the Android post, it is necessary to prepare some Java and Android knowledge, there are a lot of articles will introduce how to review the basic knowledge or advanced knowledge, or read some classic interview data. You can comb your own knowledge system according to the online articles and some data, and form one knowledge point to the surface, so that you can have a deeper understanding, and have their own focus, I will list the direction of my preparation:


1. Activity lifecycle?

onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDetroy()

2. Service life cycle?

There are two ways to start a service

  • One is throughstartService()Mode to start
  • The other is throughbindService()Mode to start.

Different startup modes have different life cycles.

The life cycle of a service started by startService() looks like this: call startService() –> onCreate()–> onStartConmon()–> onDestroy(). In this way to start, you need to pay attention to a few issues:

  • One: when we passstartServiceAfter being called, the call is repeated several timesstartService(),onCreate()The method is called only once, andonStartConmon()Will be called multiple times when we callstopService()The time,onDestroy()Will be called to destroy the service.
  • Second: when we passstartServiceAt startup, a value is passed in the intentonStartConmon()When fetching a value from the intent, be sure to check whether the intent is null.

Bind with bindService(), which binds the service lifecycle: BindService –>onCreate()–>onBind()–>unBind()–>onDestroy() bindService If you want to call it in an activity, you need to get the ServiceConnection object in the activity, and then use the ServiceConnection to get the class object of the inner class in the service, and then use this class object to call the method in the class. Of course this class needs to inherit from Binder objects

3. The Activity startup process (don’t answer the lifecycle)

There are two scenarios for app startup

  • The first is from the desktoplauncherClick on the corresponding app icon
  • The second is through calls in the activitystartActivityTo start a new oneThe 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 methods and differences

Extended here: 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 broadcast, and it’s affected by the life cycle, when you exit the page, you don’t get 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

Extended here: what kind of request is used in Volley

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. A more classic framework volley, before Android 2.3 version is the use of Android HttpClient, after Android 2.3 using HttpUrlConnection.

2. Intermediate → Advanced knowledge system

6. Differences between Java virtual Machine and Dalvik Virtual Machine

Java Virtual machine:

  • javaVirtual machines are based on stacks.

    Stack-based machines must use instructions to load and manipulate data on the stack, and many more instructions are required.
  • javaThe virtual machine worksjavaBytecode.

    javaClasses are compiled into one or more bytecodes.classFile.

Dalvik virtual machine:

  • dalvikVirtual machines are register-based
  • DalvikThe run is custom.dexBytecode format.

    When a Java class is compiled into a.class file, it passes adxThe utility converts all. Class files into one.dexFile, and thendalvikThe virtual machine reads instructions and data from it.
  • The constant pool has been modified to use only 32-bit indexes to simplify the interpreter.
  • One application, one virtual machine instance, one process

    All Android applications have one threadlinuxThreads run in their own sandbox, and different applications run in different processes. Each androiddalvikApplications are given a separatelinux PID(app_*)
7. Process survival (undead process)

Extending here: What is the priority of the process

The current Android process preservation methods are mainly divided into black, white, and gray. The general implementation ideas are as follows: Black preservation: Different APP processes wake up each other with broadcasts, including those provided by the system.

  • White: Start foreground Service
  • Grey Protection: Start foreground Service using system vulnerability

Black preservation the so-called black preservation 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: Adding a third partySDKIt also wakes up the corresponding APP process, such as wechatsdkWill wake up wechat, alipaysdkWill 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 preservation The white preservation method is very simple, that is, 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.

Grey to keep alive grey to keep alive, this means of keeping alive 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. Idea 2: API >= 18, start two foreground services with the same ID at the same time, and then stop the Service with the same ID. For those familiar with Android system, it is known that the system does not kill the process when the APP goes back to the background for the sake of experience and performance. I cache it. 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(Foreground process)
  • Visible process(Visible process)
  • Service process(Service process)
  • Background processes(Background process)
  • An empty process(Empty process)

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 recycle common APP processes. The oOM_adj of system processes can be less than 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 that is the original root View. 3: ViewRoot adds views one by one through addView method. WindowManagerService receives the message and calls back to 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:

  • Queue first in first out, stack first in last out
  • “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.
  • Traverse data at different speeds

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

SingleTop if an instance of the Activity happens to exist at the top of the task’s stack, it is reused (the onNewIntent() of the instance 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, a new instance is created as long as it is not at the top of the stack. Use scenarios such as content pages of news or reading apps.

SingleTask reuses an instance of the Activity if it already exists on the stack (its onNewIntent() is called). 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.

The singleInstance pattern creates an instance of the Activity in a new stack and lets multiple applications share the Activity instance in 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. 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:

  • Draw the view’s background;
  • Save the Layer of the canvas.
  • Draw the contents of the View;
  • Draw a View subview, if not use;
  • Restore Layer;
  • Draws a scroll bar.
View, ViewGroup event distribution

1. There are only two main actors 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 ViewGroup 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.

7. OnInterceptTouchEvent has two functions:

  • Intercept the distribution of Down events.
  • Abort Up and Move events are passed to the target View so that the target View is locatedViewGroupCapture 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.

15. Several ways to communicate across processes in Android

Android communicates across processes, like IntEnts and contentProviders. Broadcasts and services can communicate 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, such as AIDL

Broadcast: Broadcast includes static broadcast and dynamic broadcast.

Advanced knowledge system

16. AIDL understands

Extend here: Brief introduction to Binder

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 sub-BasedexClassLoader, and under the BaseDexClassLoader there is an array — DexPathList, which is used to store dex files. When a BaseDexClassLoader calls the findClass method, it actually iterates through the array to find the corresponding dex file. If it finds the dex file, it returns it directly. The solution to the hot fix is to add the new dex to the set before the old dex, so it will be taken out first and return.

20. Android memory leaks and management
  • Memory overflow (OOM) and memory leaks (objects cannot be reclaimed).
  • Causes of memory leaks
  • 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

Memory leakage causes: 1. Memory leakage caused by Handler. Solution: If you declare Handler as a static inner class, you do not 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 use weak references to the outer class

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
  • Directly in aFragmentCall the other one inFragmentThe methods in
  • Use interface callbacks
  • Use the radio
  • Fragment calls the public method of the Activity directly
22. Android UI adaptation

Font sp, DP, match_parent, WRap_content, weight image resources, different image resolution, in the corresponding folder can be replaced by percentage.

23. App optimization

App optimization:

Tool: Hierarchy Viewer Analysis layout tool: TraceView Test analysis time

App Startup optimization

Layout optimization response optimization Memory optimization battery usage optimization network optimization

There are three startup modes for the App: Cold start: The App was not started or the App process was killed. The App process does not exist in the system.

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.

Startup optimization: onCreate of Application (especially third-party SDK initialization), rendering of the first screen of Activity should not be time-consuming, if any, can be put into child threads or IntentService.

Layout optimization should not be too complex for nesting. You can use

,

,


Response optimization the Android system redraws our interface (Activity) with a VSYNC signal every 16ms.

The causes of page stalling are as follows: (1) overly complex layouts, (2) complex operations by UI threads, and (3) frequent GC leads to frequent GC for two reasons: (1) memory jitter, when a large number of objects are created and released in a short period of time, and (2) a large number of objects are created in a short period of time.

Battery usage optimization tool: Batterystats & Bugreport

(1) Optimize network request (2) Use GPS in positioning, please remember to turn off in time

Network optimization The impact of Network connection on users: 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, (2) The scale of the image is recommended by the SDK to be an index value of 2, the larger the value, the less clear the image. (3) Use the recycle() method to recycle images

HybridApp WebView interacts with JS

Android and JS call each other through WebView method, in fact: Android to call JS code

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. 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

  • throughWebViewtheAddJavascriptInterface ()Object mapping, this method is simple to use, only the Android object and JS object mapping, but there are relatively large vulnerabilities.

    The reason for the vulnerability is that when JS gets the Android object, it can call all the methods in the Android object, including the system class(Java. Lang. Runtime class)To perform arbitrary code execution.

Solutions:

(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.

  • throughWebViewClienttheshouldOverrideUrlLoading ()Method callback intercepts url.

    Advantages of this approach:

    There are no mode 1 vulnerabilities;

    Disadvantages: JS gets the return value of the Android method is complicated. (Ios mostly uses this approach.)

(1)Android intercepts the URL with shouldOverrideUrlLoading (), the callback method of WebViewClient. (2) The protocol that parsed the URL. (3) If it detects a pre-agreed protocol, it calls the corresponding method

  • throughWebChromeClientonJsAlert(),onJsConfirm(),OnJsPrompt ()Method callback intercepts JS dialogs alert(), confirm(), prompt () messages

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

The core idea of the garbage collection algorithm is to identify objects in the available memory space of the VIRTUAL machine, that is, the heap space. If an object is being referenced, it is called a viable object; otherwise, if the object is no longer referenced, it is a garbage object, and the space it occupies can be reclaimed for redistribution. The selection of garbage collection algorithm and reasonable adjustment of garbage collection system parameters directly affect system performance.

27, ANR

ANR full name Application Not Responding. If an operation cannot be handled by the system for a period of time, the ANR dialog box shown in the preceding figure is displayed on the system layer.

Causes:

(1) The BroadcastReceiver cannot respond to user input events (such as keyboard input and touch screen) within 5s. (2) the BroadcastReceiver cannot end within 10s. (3) The BroadcastReceiver cannot end within 20s (low probability)

Solution:

(1) Do not do time-consuming operations in the main thread, but should be implemented in child threads. Do as few create operations as possible in onCreate() and onResume(). (2) Applications should avoid time-consuming operations or calculations in BroadcastReceiver. (3) Avoid launching an Activity in an Intent Receiver, because it creates a new screen and steals focus from the program the current user is running. (4) A service runs on the main thread, so time-consuming operations in a service must be performed on a child thread.

28. Design patterns

The Double Check is required to be written. Singleton mode: divided into evil and lazy evil:

public class Singleton 
{ 
    private static Singleton instance = new Singleton(); 
    public static Singleton getInstance() 
    { 
        returninstance ; }}Copy the code

LanHanShi:

public class Singleton02 
{ 
   private static Singleton02 instance; 
   public static Singleton02 getInstance() 
   { 
       if (instance == null) 
       { 
           synchronized (Singleton02.class) 
           { 
               if(instance == null) { instance = new Singleton02(); }}}returninstance; }}Copy the code
MVP, MVC, MVVM

Extension here: The handwritten MVP example, the difference between MVC, the MVP advantage

MVP mode corresponds to Model: business logic and entity Model, View mode corresponds to activity, is responsible for drawing view and interaction with user, Presenter mode is responsible for interaction between view and Model.

On the basis of MVC mode, THE MVP mode completely separates Model and View to lower the coupling of the project. In MVC, the activity in the project corresponds to C–Controllor in MVC, and the logical processing in the project is processed in this C. Meanwhile, the interaction between View and Model. In other words, all of the logical interactions and user interactions in MVC are in the Controllor, which is the activity. View and Model can communicate directly. In MVP mode, the Model business logic and entity Model are separated more thoroughly and the division of labor is more clear. The view is responsible for the interaction between the user and the Presenter is responsible for the interaction between the view and the Model. The biggest difference between MVP and MVC is that MVC allows the interaction between the Model and view. In MVP, it is clear that the interaction between the Model and View is done by Presenter. The other thing is that presenters interact with views through interfaces

30, JNI

(1) Install and download Cygwin, download Android NDK (2) design of JNI interface in NDK project (3) use C/C++ implementation of local methods (4)JNI generate dynamic link library. So file (5) copy dynamic link library to Java project, call in Java project, Run the Java project

RecyclerView and ListView difference

RecyclerView can complete the effect of ListView,GridView, can also complete the effect of waterfall flow. You can also set the scrolling direction of the list (vertical or horizontal). RecyclerView view reuse does not require developers to write their own code, the system has helped complete the packaging. RecyclerView can be used for local refresh. RecyclerView provides an API to animate items.

In terms of performance: If you need to refresh data frequently and need to add animation, RecyclerView has great advantages. If presented as a list, the difference is not that great.

4. The NDK

More complete project download. To be continued. The source code. Github. You can click about me to contact me