Remote interviews byte beat Kong Android development, just to get the offer, knowledge sharing

 

Beijing is now very strict prevention and control, particularly in the field to be returned particularly troublesome. Because not convenient to go out, the interview is mainly telephone, video and other ways.

2020 summary of the latest wave of interview questions, we want to help! Behind the answer is self-organize, if imperfect, please correct me!

table of Contents:

1. Network
2.Java container base & & & synchronization pattern design
3.Java & virtual machine memory structures the GC & & & loading four kinds of class reference dynamic proxy &
4.Android performance optimization based & Framwork &
5.Android & modular heat hot fix & update & packaging & confused & compression
6. audio and video player & FFmpeg &

1, the network

Network protocol model

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

Transport Layer : The base-end communication for the two hosts
TCP, UDP

Network layer : a control packet transmission, routing and other
IP

Link layer : operating system device drivers, network card interfaces

TCP and UDP difference

TCP connection; reliable; ordered; byte stream oriented; slow; more by weight; full; suitable for file transfer, browser, etc.

  • Full duplex: A to B while the message, B A hair also give
  • Half Duplex: A to B while the message, B can not be sent to the A

Connectionless UDP; unreliable; disorder; for the message; speed; lightweight; applies to instant messaging, video calls, etc.

TCP three-way handshake

A: Can you hear me?
B: I can hear, can you hear me?
A: I can hear, I began

A and B both have to be able to ensure that: I say, can you hear; what you say, I can hear. It needs three-way handshake

TCP four wave

A: I finished
B: I know, wait a minute, I could not finish
B: I finished
A: I know, it ended

A B received after the end of the message B could not finish, could not immediately respond to the end of the mark, and so finished only after telling A: I'm done.

POST and GET difference

Get parameter in the url; Post parameters on request Body in
Get potentially unsafe, because the parameters in the url

HTTPS

HTTP Hypertext Transfer Protocol, cleartext; the HTTPS protocol HTTP using SSL encrypts the transmission data

The default HTTP port 80; HTTPS default port 443

Advantages: Security
Disadvantages: time-consuming, SSL certificate fees, encryption capability is still limited, but much stronger than HTTP

2, Java foundation & Containers & sync & Design Patterns

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

  • Thread-safe StringBuffer, StringBuilder thread-safe
  • + StringBuilder is actually implemented, so the body can be directly used acyclic +, the loop body is not, as frequently create StringBuilder
  • String.concat essence new String, low efficiency, time-consuming sorting: StringBuilder <StringBuffer <concat <+

Java generics erased

  • Modified class structure member variables related to generics will not be erased
  • Generic container class is erased

ArrayList、LinkedList

ArrayList

Array-based implementation, Fast Find: o (1), Slow additions: o (n)
an initial capacity of 10, by the expansion method System.arrayCopy

LinkedList

O (n), deletions fast:: implement a doubly linked list, based on a slow look o (1)
encapsulates the call stack and queue

HashMap 、HashTable

HashMap

  • Based on arrays and linked lists, an array of HashMap is subject; the list is to resolve hash collision exists
  • When a hash collision occurs and the chain will be greater than a threshold size expansion, JAVA 8 will improve the performance of the linked list into a red-black tree
    to allow key / value is null

HashTable

  • The same data structure and HashMap
  • Does not permit value is null
  • Thread Safety

ArrayMap、SparseArray

ArrayMap

1. implemented based on two arrays, a store the hash; a store pairs. Expansion of the array when only copy, do not need to rebuild the hash table
2. high memory utilization
3. unsuitable store large amounts of data, because the key will be a binary search (1,000)

SparseArray

1. Based on two arrays, int do key
2. high memory utilization
3. unsuitable store large amounts of data, because the key will be a binary search (1,000)

volatile keyword

  • Can only be used to modify variables for modifying variables may be simultaneously accessed by multiple threads
  • Equivalent lightweight synchronized, volatitle ensure orderly (disable command reordering), visibility; the latter also guarantee atomicity
  • Variables in the main memory, each thread also has its own working memory, working memory variable in its own thread of copies have taken, this thread is operated directly copy
  • After being modified volatile variable changes will be synchronized to the main memory immediately, to maintain the visibility of variables.

Double-check a single case, why should we increase volatile?

1.volatile want to solve the problem is that you want to use instance, we found that instance in another thread! = Null, but in fact has not been initialized instance of this problem

2. instance = newInstance (); split into three sentences Yes. 3. 1. 2. Initialize the memory allocation instance pointer to the allocated memory space

3.volatile prohibition instruction can be reordered to ensure the implementation of the first 2, 3 after performing

wait 和 sleep

  • Thread of sleep is a static method, you can call anywhere
  • wait a member of the Object methods can only be called in synchronized code block, otherwise it will report an abnormal state monitoring illegal IllegalMonitorStateException
  • sleep will not release a shared resource lock, wait a shared resource lock is released

lock 和 synchronized

  • Java is synchronized keyword, built-in features; Lock is an interface
  • synchronized automatically release the lock; Lock require manual release, it is necessary to write and finally release the lock try catch block
  • synchronized can not be interrupted to wait for a lock; lock can be interrupted
  • Lock multiple threads can improve read / write operations efficiency
  • When the fierce competition for resources, performance will be significantly better than the lock synchronized

Reentrant lock

  • Definition: Having acquired lock, called again synchronized block / do not have to try to re-apply lock when acquiring a lock, you can execute code directly related
  • ReentrantLock are synchronized and locked reentrant

Fair locks

  • Definition: The longest waiting time thread priority access lock
  • Unfair lock can not guarantee which thread to acquire the lock, synchronized lock is unfair
  • When ReentrantLock default unfair lock can be set to lock fair

Optimistic and pessimistic locking

  • Pessimistic lock : Once a thread lock, other threads hangs wait for the write operation frequent scene; synchronized is pessimistic locking
  • Optimistic locking : Suppose there is no conflict, no lock, to determine whether the data expired when updating data, updating expired, then not performed for read-intensive operation scene
  • Optimistic locking CAS : the Compare And Swap, update data to compare the original value are equal, not equal then the data in the past, no data update
  • Optimistic locking achieve : AtomicInteger, AtomicLong, AtomicBoolean

Four necessary conditions for deadlock

  • Exclusive
  • Possession and wait
  • Not seize
  • Circular wait

synchronized principle

  • Each object has a lock Monitor: monitor, monitorenter sync block is executed as start, end motnitorexit
  • wait / notify monitor dependent on the monitor, so the asynchronous execution code block will be reported abnormal IllegalMonitorStateException

3, Java Virtual Machine & memory structure & GC & class loader & references & four kinds of dynamic proxies

JVM

  • Definition: the computer can be understood as a fictional interpretation of its own bytecode instruction set is mapped to the instruction set of the local CPU or OS, just focus on the upper Class document, regardless of operating system, cross-platform
  • Kotlin is able to explain to Class files, so you can run on the JVM

JVM memory model

  • Between Java Multithreading is to communicate through shared memory, each thread has its own local memory
  • Shared variables stored in the main memory, the thread variable to the local copy of the shared memory
  • volatile memory model keyword is to give services, to ensure the visibility and order of memory

JVM memory structure

Thread-private :

1. Program Counter: the recording instruction address byte code being executed, if the method is being performed Native null
2. virtual machine stack: the time required to perform a method as a method for data stored stack frame on the stack, the stack is performed after
3. the native method stacks: stack with a virtual machine, but for a native method

Threads share :

1. heap: Java instance storage, GC main areas, generational collection GC method will now heap is divided into the new generation, the old year
2. Method area: storage class information, constant pool, static variables and other data

GC

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

Recycling Type:

1. objects in the heap

  • Generational GC collected heap method will now be divided into the new generation, old years
  • New Generation: New small objects into the new generation; algorithm to be recovered by copying
  • Old year: new large object, and the object will enter the old years old; by mark - sweep algorithm to be recovered

2. The method of class information region, constant pool

Determining whether an object can be recovered:

1. Reference counting
disadvantages: circular reference

2. reachability analysis
Definition: to start the search from GC ROOT, unreachable objects are can be recycled

GC ROOT

1. The target virtual machine stack / native method stacks referenced
2. The method area in constant / static variables referenced objects

Four kinds of reference

  • Strong Quote: will not be recovered
  • Soft references: will be recycled out of memory
  • Weak References: will be recycled when gc
  • False quote: Could not get virtual objects by reference, you can monitor the recovery of objects

ClassLoader

Class life cycle:

1. Load; 2. Verify;. Preparation 3; 4. Analytical; 5 initialization; use 6; 7 unloaded.

Class loading process:

1. Load: Get Class binary byte stream; generating method operating zone of the storage structure; generating Class object in memory
2. Verify: Class byte stream conforming to ensure that the requirements of the virtual machine
3. Preparation: initialize static variables
4. Analysis: symbol the constant pool directly replace references cited
5. initialization: perform a static block code class variable assignment

Class loading timing :

Examples of object 1.
2. static method call class
3. Call static class variables (except the constant into the constant pool)

Class loader: responsible for loading class files

classification:

1. bootstrap class loader - no parent class loader
2. expanding class loader - inherited from the bootstrap class loader
3. System class loader - inherited from class loader Development

Parents delegation model:

When you want to load a class, will make up the first layer by layer parent loader to load, load will fail to load it

Why is it called the parents? Do not consider a custom loader, the system class loader needs to ask two online, so called parents

Determining whether a class is the same, in addition to the class information must be the same also when a class loader

advantage:

  • Prevent repeated loading, the parent loader loads over there is no need to load up
  • Security to prevent tampering with the core class libraries

Dynamic proxy principle and implementation

  • InvocationHandler interfaces, dynamic proxy class needs to implement this interface
  • Proxy.newProxyInstance, used to dynamically create proxy object
  • Application Retrofit: Retrofit by dynamic proxy, as defined in our request interface generates a dynamic proxy object, fulfill the request

4, Android & basic performance optimization & Framwork

Activity Start Mode

  • Standard Mode standard
  • singleTop multiplexing mode stack,
    • Push-click on the message interface
  • SingleTask the multiplexing mode stack,
    • Home
  • singleInstance singleton pattern, a single task in a stack
    • Call interface
      details:
    • taskAffinity: task dependencies, task stack is used to specify the name, the default name for the application package
    • allowTaskReparenting: allowing the transfer task stack

View works

  • DecorView (Frame Layout)
    • LinearLayout
      • titlebar
      • Content
      • View call set setContentView

performTraversals method call trigger ViewRoot View start drawing, and then in turn call:

  • performMeasure: View of traversing measurements measure
  • performLayout: traversing View layout to determine the position of
  • performDraw: View of the draw traversal draw

Event distribution mechanism

  • After a MotionEvent generated by Activity -> Window -> decorView -> View transfer order, View event distribution transfer process is mainly dependent on three methods:
  • dispatchTouchEvent: for distribution event, as long as receive a click event will be called, returns a result indicating whether the consumed current events
  • onInterceptTouchEvent: used to determine whether to intercept the event, when ViewGroup sure you want to intercept events, the sequence of events will no longer trigger a call to this ViewGroup of onIntercept
  • onTouchEvent: event for processing and returns the result indicating whether the current event is passed to the untreated parent container treatment
  • detail:
    • A sequence of events can only be intercepted and consumes a View
    • View onIntercept no way to directly call processing onTouchEvent
    • OnTouchListener higher priority than OnTouchEvent, onClickListener lowest priority
    • requestDisallowInterceptTouchEvent shield can call a method of the parent container onIntercet

Window, windowmanager, WMS, SurfaceFlinger

  • Window : abstraction is not a physical, but in the form View of existence, achieved through PhoneWindow
  • WindowManager : Window outside the entrance access, interact with the internal WMS is a process IPC
  • The WMS : layout and order management window Surface as a system-level service in a single process run
  • SurfaceFlinger : WMS maintenance window will be displayed on the screen in a certain order mixed

View animation, frame animation and animation properties

View animation:

  • The role of targeted View, available xml definition, suggestions xml achieve more legible
  • It supports four effects: translation, scaling, rotation, transparency

Frame animation:

  • By AnimationDrawable implementation, easy OOM

Property animation:

  • May be applied to any object, can be defined xml, Android 3 is introduced, more flexible code implementation recommendations
  • Including ObjectAnimator, ValuetAnimator, AnimatorSet
  • Time interpolator: current percentage is calculated by the percentage change properties lapse of time
  • System Preferences constant speed, acceleration, deceleration interpolator
  • Type estimator: changed attribute value is calculated based on the percentage change of current attributes
  • System Preferences integer, floating point, and other types of color values ​​estimator
  • Caution:
  • Avoid using animation frames, easy OOM
  • Stop animation destroyed interface, to avoid memory leaks
  • Open hardware acceleration, improve fluency animation, hardware acceleration:
  • The work-sharing part of the cpu to gpu, gpu completed using drawing work
  • From the two aspects of the work-sharing mechanisms and draw optimized rendering speed

Handler、MessageQueue、Looper

  • Handler: the development of direct contact with the class, and internal hold MessageQueue Looper
  • MessageQueue: the message queue, the message is stored inside a single linked list
  • Looper: internal hold MessageQueue, cycle to see if there are new messages have to deal with, not to clog
  • How to achieve blocking: by nativePollOnce method, based on Linux epoll event management mechanism
  • Why will not the main thread Looper blocked: every 16ms refresh UI system will send a wake-up message

MVC、MVP、MVVM

  • MVP: Model: processing data; View: controlling view; Presenter: Separation and Model Activity
  • MVVM: Model: acquiring process data stored; View: controlling view; ViewModel: data container
    • Use Jetpack component architecture LiveData, ViewModel easy to achieve MVVM

Serializable、Parcelable

  • Serializable: Java serialization for storage and network transmission, serialVersionUID used to determine the anti-serialization and class version is consistent, inconsistent deserialization failed back
  • Parcelable: Android serialization mode for transmitting communication data component, high performance, because unlike Serializable as a large reflection operation, frequent GC

Binder

  • Android mainstay of communication between processes, based on a client - server communication
  • Mmap a copy of data achieved using the IPC, the traditional IPC: A User Space -> Kernel -> User Space B; B mmap the kernel and user space mapping, from a user A spatial direct -> User B space
  • BinderPool to avoid creating a multi-Service

IPC way

  • Intent extras, Bundle: communicating data be serialized required to achieve Parcelable, Serializable, four components apply to the communication
  • File Sharing: For simple data exchange is not high real-time scenes
  • AIDL: AIDL the interface is essentially a system can provide us with tools to facilitate the achievement of BInder
    • Android Interface Definition Language, cross-process calls the method can be achieved
    • Server: the storm drain to the client interface declaration in AIDL file, create Service AIDL implement the interface and listens for client connection requests
    • Client: Bind server Service, to get into the server Binder object AIDL interface call after binding is successful
    • RemoteCallbackList cross-process, to listen, to do with a Binder object storage key clients registered listener
    • Binder monitor off: 1.Binder.linkToDeath death proxy settings; 2 onServiceDisconnected callback.
  • Messenger: Based AIDL implemented, server serial processing, mainly for messaging, many communication for low concurrency
  • ContentProvider: Based Binder achieve for many inter-process data sharing
  • Socket: TCP, UDP, for network data exchange

Android system startup process

  • Press the power button -> Load boot program to the RAM BootLoader -> commencement kernel execution BootLoader -> init process start -> start various daemons and Zygote ->
  • Start System Server service process open AMS, WMS, etc. -> Start Launcher application process

App startup process

Click on an application icon in the Launcher -> Find application process by AMS, if it exists by Zygote process fork

Process keep alive

  • . Process Priority: 1 foreground process; 2 that the process; 3 service process; 4 background processes; 5 empty process....
  • Was killed when a cut to the back out of memory; 2 manufacturers cut back power saving mechanism to kill; 3 users active cleanup: process is kill scenes...
  • Paul lifestyle:
    • 1.Activity mention the right to: 1 pixel Activity hang a priority to improve the process to the foreground process
    • 2.Service mention the right: Start a front desk (API> 18 will be running the notification bar)
    • 3. Pull broadcast live
    • 4.Service pull live
    • 5.JobScheduler regular tasks pull live
    • 6. The process of pulling double live

Network optimization and testing

  • Speed: 1.GZIP compression (okhttp automatic support); 2.Protocol Buffer alternative json; 3 optimized picture / document flow; 4.IP direct connection eliminates the need for DNS resolution time.
  • Success rate: 1 failure retry strategy;.
  • Traffic: 1.GZIP compression (okhttp automatic support); 2.Protocol Buffer alternative json; 3 optimized picture / document flow; 5 HTTP file downloads; 6 cache...
  • Optimization of protocol layers, such as http better version, etc.
  • Monitoring: Charles capture, Network Monitor to monitor traffic

UI Caton optimization

  • And to reduce the level of complexity of the layout of the controls, avoiding overdraw
  • Use include, merge, viewstub
  • Optimizing the rendering process, avoid frequent create objects in Draw, a time-consuming operation to do

Scene and avoid memory leaks

1. static variables, single cases cited strong data or resources associated with the life cycle, including EventBus
resources 2. cursors, IO streams, etc. Forget the initiative to release
3 interface associated promptly suspended animation at the time of the destruction of the interface
4. inner class to hold classes outside referenced memory leaks caused

  • Internal memory leak avoidance handler class: Class 1 using an internal static + weak reference 2. Empty message queue interface Destruction
  • Detection: Android Studio Profiler

LeakCanary principle

  • Weak references and references by monitoring whether the queue object is recovered
  • For example, when Activity began monitoring destruction of the object, detected not recovered the initiative gc, then continue to monitor

OOM scene and avoid

  • Load Big Picture: reduce picture
  • Memory leak: avoid memory leaks

5, Android modular & hot fix & heat pack update & & & compression confusion

Dalvik 和 ART

  • Dalvik
    • Google is specifically designed for the Android platform Java virtual machine can be run directly .dex file for limited memory and processing speed of the system
    • JVM is a stack-based instruction set; the Dalvik is register-based instruction set, code execution better efficiency
  • ART
    • Converting each run should Dalvik bytecodes into machine code; the ART will be translated into machine code in the application installation, execution is faster
    • ART machine code more storage space, space for time

APK packaging process

1.aapt packaged resources to generate R.java file; aidl generate java files
2. Compile the java file for the class files
3. Convert the project and the third class files into dex file
4. dex file, so, compiled resources, resources packaged into the original file apk
5. signature
6. align the resource file, to reduce the runtime memory

App installation process

  • You must first extract the APK, resources, so and so into the application directory
  • It will be treated as Dalvik dex ODEX; ART OAT will be processed into dex;
  • OAT include dex and compiled machine code during installation

Component-based routing to achieve

ARoute: parsing by APT @Route other annotations, binding JavaPoet generate routing, i.e. routing and mapping relationship of Activity

6, audio and video player & FFmpeg &

FFmpeg

A command-based approach to achieve the audio and video editing App:
https://github.com/yhaolpz/FFmpegCmd

Integrated compiled AAC, MP3, H264 encoder

Player principle

Video playback Principle: (mp4, flv) -> decapsulation -> (mp3 / aac, h264 / h265) -> decoding -> (pcm, yuv) -> audio and video synchronization -> Rendering Play

Audio and video synchronization:

  • Reference clock source: audio time stamp, the video time stamp and the external path is selected as a reference clock source (typically an audio selection, as are more sensitive to audio, ijk is the default audio)
  • Or by waiting for the frame dropping the video stream is aligned with the reference clock source, synchronized

IjkPlayer principle

Integrated MediaPlayer, ExoPlayer and IjkPlayer three implementations, which IjkPlayer based on FFmpeg's ffplay

Audio output: AudioTrack, OpenSL ES; video output: NativeWindow, OpenGL ES

 

The end of the sentence

For programmers, content knowledge to learn, there are too many technical, environmental order not to be eliminated only improve ourselves, always us to adapt to the environment, not the environment to adapt to us!

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司19年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里在石墨文档以图片的形式给大家展示一部分;
《Android架构视频+BAT面试专题PDF+学习笔记》

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

  • 无论你现在水平怎么样一定要 持续学习 没有鸡汤,别人看起来的毫不费力,其实费了很大力,这四个字就是我的建议!!!!!!!!!
  • 我希望每一个努力生活的IT工程师,都会得到自己想要的,因为我们很辛苦,我们应得的。

原文地址简书;https://www.jianshu.com/p/eb4189e5b8ab

发布了17 篇原创文章 · 获赞 0 · 访问量 167

Guess you like

Origin blog.csdn.net/chuhe1989/article/details/104304211