Android calls the system camera! Android multi-processes from beginning to end, with the real problems of Dachang

I. Introduction

Two months to hear two words most is Android prospects and job cuts , as the army was cut in one of my key words are regrettable and better .

Unfortunately , the current project still has a lot of room for imagination, but it is coming to an end; fortunately , I have not worked with a part-time mentality in the past few years after graduation. The cold winter will be cold and I am afraid of a hammer.

Recently I started to write articles again. Some friends asked me how I prepared for the interview. I also want to talk about some of my recent ideas and plans. Let's discuss it together.

The whole is divided into the following two aspects:

  • Self introduction & project experience
  • Knowledge reserve

What are the common questions and answer ideas in the Android interview

table of Contents:

1. Network 2. Java
Foundation & Container & Synchronization & Design Pattern
3. Java Virtual Machine & Memory Structure & GC & Class Loading & Four References & Dynamic Proxy
4. Android Basic & Performance Optimization & Framwork
5. Android Modularity & Hot Fixing & Hot Update & Packing & Obfuscation & Compression
6. Audio and Video & FFmpeg & Player

1. Network

Network protocol model

Application layer : responsible for handling specific application details
HTTP, FTP, DNS

Transport layer : Provide end-to-end basic communication
TCP, UDP for two hosts

Network layer : control packet transmission, routing and other
IP

Link layer : operating system device drivers, network card related interfaces

The difference between TCP and UDP

TCP connection; reliable; orderly; byte-oriented; slow speed; heavier; full duplex; suitable for file transfer, browsers, etc.

  • Full duplex: While A sends messages to B, B can also send messages to A
  • Half-duplex: While A is sending messages to B, B cannot send messages to A

UDP connectionless; unreliable; disorderly; message-oriented; fast; lightweight; suitable for instant messaging, video calls, etc.

TCP three-way handshake

A: Can you hear it?
B: I can hear it, can you hear it?
A: I can hear it, let's start

Both parties A and B must ensure that: you can hear what I say; I can hear what you say. So it needs three handshake

TCP waved four times

A: I'm finished
B: I know, wait a minute, I may not finish
B: I'm finished too
A: I know, end it

After B receives the end of A message, B may not have finished speaking, so he can't reply to the end sign immediately, and can only tell A after speaking: I'm finished.

The difference between POST and GET

The Get parameter is placed in the url; the Post parameter is placed in the request body.
Get may be unsafe because the parameter is placed in the url

HTTPS

HTTP is a hypertext transfer protocol, which is transmitted in plain text; HTTPS uses SSL protocol to encrypt HTTP transmission data

HTTP default port 80; HTTPS default port 443

Advantages: Security
Disadvantages: time-consuming, SSL certificate charges, encryption capabilities are still limited, but much stronger than HTTP

2. Java Basics & Containers & Synchronization & Design Patterns

StringBuilder, StringBuffer, +, String.concat link string:

  • StringBuffer is thread-safe, StringBuilder is not thread-safe
  • +In fact, it is realized by StringBuilder, so the non-loop body can be used directly +, but the loop body cannot, because StringBuilder will be created frequently
  • String.concat is essentially a new String, which is inefficient and time-consuming to sort: StringBuilder <StringBuffer <concat <+

Java generic erasure

  • Generics related to class structure such as modified member variables will not be erased
  • Container generics will be erased

ArrayList、LinkedList

ArrayList

Based on array implementation, fast search: o(1), slow addition and deletion: o(n) with
an initial capacity of 10, and expansion through the System.arrayCopy method

LinkedList

Implementation based on doubly linked list, slow search: o(n), fast addition and deletion: o(1)
encapsulates the call of queue and stack

HashMap 、HashTable

HashMap

  • Based on the implementation of arrays and linked lists, arrays are the main body of HashMap; linked lists exist to resolve hash conflicts
  • When a hash conflict occurs and the linked list size is greater than the threshold, it will expand. JAVA 8 will convert the linked list to a red-black tree to improve performance.
    Allow key/value to be null

HashTable

  • The data structure is the same as HashMap
  • Value is not allowed to be null
  • Thread safe

ArrayMap、SparseArray

ArrayMap

1. Based on two arrays, one stores the hash; the other stores key-value pairs. When expanding capacity, only array copy is needed, no need to rebuild the hash table
2. High memory utilization
3. Not suitable for storing a large amount of data, because the key will be dichotomized search (below 1000)

SparseArray

1. Implementation based on two arrays, int as key
2. High memory utilization
3. Not suitable for storing a large amount of data, because the key will be searched dichotomously (below 1000)

volatile keyword

  • Can only be used to modify variables, applicable to modify variables that may be accessed by multiple threads at the same time
  • Equivalent to lightweight synchronized, volatitle can guarantee order (instruction reordering is disabled) and visibility; the latter can also guarantee atomicity
  • Variables are located in the main memory, each thread also has its own working memory, the variable has a copy in the working memory of its own thread, and the thread directly manipulates this copy
  • The variable modified by volatile will be synchronized to the main memory immediately after it is changed to maintain the visibility of the variable.

Double check singleton, why add volatile?

1. The problem that volatile wants to solve is that you want to use instance in another thread and find instance!=null, but in fact the instance has not been initialized yet.

2. Split instance = newInstance(); into 3 sentences. 1. Allocate memory 2. Initialize 3. Point instance to the allocated memory

3. Volatile can prohibit instruction reordering, make sure to execute 2 first, then execute 3

wait 和 sleep

  • sleep is a static method of Thread, which can be called anywhere
  • wait is a member method of Object, it can only be called in the synchronized code block, otherwise it will report IllegalMonitorStateException.
  • sleep will not release the shared resource lock, wait will release the shared resource lock

lock 和 synchronized

  • synchronized is a Java keyword, a built-in feature; Lock is an interface
  • Synchronized will automatically release the lock; lock needs to be manually released, so you need to write to the try catch block and release the lock in finally
  • synchronized cannot interrupt waiting for the lock; lock can be interrupted
  • Lock can improve the efficiency of multiple threads for read/write operations
  • When competition for resources is fierce, the performance of lock will be significantly better than synchronized

Reentrant lock

  • Definition: After the lock has been acquired, the synchronization code block is called again/when trying to acquire the lock, there is no need to apply for the lock again, and the relevant code can be executed directly
  • ReentrantLock and synchronized are both reentrant locks

Fair lock

  • Definition: The thread with the longest waiting time will get the lock first
  • Unfair locks cannot guarantee which thread acquires the lock. Synchronized is an unfair lock
  • ReentrantLock is a non-fair lock by default and can be set as a fair lock

Optimistic and pessimistic locking

  • Pessimistic lock : Once a thread gets the lock, other threads will hang and wait, which is suitable for scenarios with frequent write operations; synchronized is a pessimistic lock
  • Optimistic lock : Assuming that there is no conflict, no lock, judge whether the data is expired when updating the data, if it expires, the data will not be updated, suitable for scenarios with frequent read operations
  • Optimistic lock CAS : Compare And Swap, first compare whether the original value is equal when updating the data, if it is not equal, it means that the data is in the past, and the data is not updated
  • Optimistic lock implementation : AtomicInteger, AtomicLong, AtomicBoolean

4 necessary conditions for deadlock

  • Mutually exclusive
  • Hold and wait
  • Not preemptable
  • Loop waiting

synchronized principle

  • Each object has a monitor lock: monitor, the synchronization code block will execute monitorenter start, motnitorexit end
  • wait/notify relies on the monitor monitor, so IllegalMonitorStateException will be reported when executed in an asynchronous code block

3. Java virtual machine & memory structure & GC & class loading & four kinds of references & dynamic proxy

JVM

  • Definition: It can be understood as a fictitious computer, explaining that its bytecode instruction set is mapped to the instruction set of the local CPU or OS. The upper layer only needs to pay attention to the Class file, which has nothing to do with the operating system, and realizes cross-platform
  • Kotlin can be interpreted as a Class file, so it can run on the JVM

JVM memory model

  • Java multi-threads communicate through shared memory, and each thread has its own local memory
  • The shared variable is stored in the main memory, and the thread will copy a shared variable to the local memory
  • The volatile keyword serves the memory model to ensure memory visibility and order

JVM memory structure

Thread private :

1. Program counter: Record the bytecode instruction address being executed, if the Native method is being executed, it will be empty
2. Virtual machine stack: When executing the method, save the data required by the method as a stack frame and put it on the stack, and then pop it out after the execution is complete.
3. Native method stack: the same as the virtual machine stack, but for the Native method

Thread sharing :

1. Heap: store Java instances, the main area of ​​GC, the generational collection of GC method will divide the heap into new generation and old generation
2. Method area: storage class information, constant pool, static variables and other data

GC

Recovery area: only for the heap and method area; the data in the private area of ​​the thread will be destroyed with the end of the thread, without recycling

Recycling type:

1. Objects in the heap

  • The generational collection GC method will divide the heap into the new generation and the old generation
  • Cenozoic: New small objects will enter the Cenozoic era; objects are recycled through the replication algorithm
  • Old age: New large objects and old objects will enter the old age; objects are recycled through the mark-sweep algorithm

2. Class information and constant pool in the method area

Determine whether an object can be recycled:

1. Reference counting method
Disadvantages: circular references

2. Reachability analysis method
Definition: start searching from GC ROOT, unreachable objects can be recovered

GC ROOT

1. Objects referenced in the virtual machine stack/local method stack
2. Objects referenced by constants/static variables in the method area

Four references

  • Strong references: will not be recycled
  • Soft references: will be recycled when the memory is insufficient
  • Weak reference: will be recycled when gc
  • Phantom reference: The object cannot be obtained through a virtual reference, and the recycling of the object can be monitored

ClassLoader

The life cycle of the class:

1. Load; 2. Verify; 3. Prepare; 4. Analyze; 5. Initialize; 6. Use; 7. Unload

Class loading process:

1. Load: get the binary byte stream of the class; generate the runtime storage structure of the method area; generate the Class object in the memory
2. Verification: ensure that the Class byte stream meets the requirements of the virtual machine
3. Preparation: initialize static variables
4. Analysis: replace the symbol reference of the constant pool with a direct reference
5. Initialization: execute static block code, class variable assignment

Class loading timing :

1. Instantiate the object
2. Call the static method of the
class 3. Call the static variable of the class (except for the constants placed in the constant pool)

Class loader: responsible for loading class files

classification:

1. Boot class loader-no parent class loader
2. Extended class loader-inherited from the boot class loader
3. System class loader-inherited from the extended class loader

Parent delegation model:

When loading a class, it will first load the parent loader layer by layer, and load it by itself when it fails.

Why are you called parents? Regardless of the custom loader, the system class loader needs to ask two layers online, so it is called the parent

When judging whether it is the same class, in addition to the class information, the same class loader must also be used

advantage:

  • Prevent repeated loading, there is no need to load after the parent loader has been loaded
  • Security, prevent tampering with core library classes

Principle and Implementation of Dynamic Agent

  • InvocationHandler interface, dynamic proxy class needs to implement this interface
  • Proxy.newProxyInstance, used to dynamically create proxy objects
  • Retrofit application: Retrofit uses dynamic proxy to generate a dynamic proxy object for our defined request interfaces to implement requests

4. Android basic & performance optimization & Framwork

Activity start mode

  • standard standard mode
  • singleTop stack top multiplexing mode,
    • Push click message interface
  • SingleTask in-stack reuse mode,
    • Home page
  • singleInstance singleton mode, located in a single task stack
    • Call interface
      details:
    • taskAffinity: task dependency, used to specify the name of the task stack, the default is the application package name
    • allowTaskReparenting: Allow task stack transfer

How View Works

  • DecorView (FrameLayout)
    • LinearLayout
      • titlebar
      • Content
      • View set by calling setContentView

The performTraversals method call of ViewRoot triggers the start of the drawing of the View, and then it will be called in turn:

  • performMeasure: traverse View's measure to measure the size
  • performLayout: Traverse the layout of the View to determine the position
  • performDraw: Traverse the draw drawing of View

Event distribution mechanism

  • After a MotionEvent is generated, it is delivered in the order of Activity -> Window -> decorView -> View. The View delivery process is event distribution, which mainly relies on three methods:
  • dispatchTouchEvent: Used to distribute events, it will be called as long as the click event is received, and the return result indicates whether the current event is consumed
  • onInterceptTouchEvent: used to determine whether to intercept the event, when the ViewGroup determines to intercept the event, the sequence of events will no longer trigger the onIntercept that calls this ViewGroup
  • onTouchEvent: used to process events, the returned result indicates whether the current event has been processed, and it will be passed to the parent container for processing if it is not processed
  • detail:
    • An event sequence can only be intercepted and consumed by one View
    • View has no onIntercept method, and directly calls onTouchEvent to handle it
    • OnTouchListener has a higher priority than OnTouchEvent, and onClickListener has the lowest priority
    • requestDisallowInterceptTouchEvent can shield the call of the parent container's onIntercet method

Window 、 WindowManager 、 WMS 、 SurfaceFlinger

  • Window : The abstract concept does not actually exist, but exists in the form of View, implemented by PhoneWindow
  • WindowManager : The entrance to the outside world to access Window, the internal interaction with WMS is an IPC process
  • WMS : Manage the layout and order of the window Surface, run as a system-level service in a single process
  • SurfaceFlinger : The windows maintained by WMS are mixed in a certain order and displayed on the screen

View animation, frame animation and attribute animation

View animation:

  • The function object is View, which can be defined by xml, and it is recommended that xml is more readable
  • Support four effects: translation, zoom, rotation, transparency

Frame animation:

  • Realized by AnimationDrawable, easy OOM

Property animation:

  • Can act on any object, can be defined by xml, and introduced by Android 3. It is recommended that the code implementation is more flexible
  • Including ObjectAnimator, ValuetAnimator, AnimatorSet
  • Time Interpolator: Calculate the percentage of the current attribute change based on the percentage of time elapsed
  • The system presets interpolators such as uniform speed, acceleration, deceleration, etc.
  • Type estimator: calculate the changed attribute value based on the percentage of the current attribute change
  • System preset integer, floating point, color value and other types of estimators
  • Precautions for use:
  • Avoid using frame animation, easy to OOM
  • Stop the animation when the interface is destroyed to avoid memory leaks
  • Turn on hardware acceleration to improve animation fluency, hardware acceleration:
  • Part of the work of the cpu is shared with the gpu, and the gpu is used to complete the drawing work
  • Optimized the drawing speed from two aspects of work sharing and drawing mechanism

At last

For Android programmers, I have compiled some materials for you, including not limited to advanced UI, performance optimization, architect courses, NDK, hybrid development (ReactNative+Weex) WeChat applets, Flutter and other all aspects of Android advanced Practicing technology; I hope to help you, and save everyone's time to search for information on the Internet to learn, and you can also share dynamics with friends around you to learn together!

  • Android Frontier Technology Outline

  • Full set of systematic high-level architecture videos

Information collection: Like + click on GitHub to get it for free

Previous Android advanced architecture materials, source code, notes, and videos. Advanced UI, performance optimization, architect courses, hybrid development (ReactNative+Weex) all aspects of Android advanced practical technology, and there are technical experts in the group to discuss, communicate and solve problems.

[External link image is being transferred...(img-RMy9ObQD-1614574795669)]

Information collection: Like + click on GitHub to get it for free

Previous Android advanced architecture materials, source code, notes, and videos. Advanced UI, performance optimization, architect courses, hybrid development (ReactNative+Weex) all aspects of Android advanced practical technology, and there are technical experts in the group to discuss, communicate and solve problems.

Guess you like

Origin blog.csdn.net/m0_52308677/article/details/114260414
Recommended