当前位置:网站首页>Android interview classic, 2022 Android interview written examination summary

Android interview classic, 2022 Android interview written examination summary

2022-07-05 19:42:00 InfoQ

Basic information

I am an ordinary undergraduate ,Android Development post .

This article is mainly a summary of autumn recruitment interview experience , Finally got Baidu 、 Tencent's offer.

It mainly includes three sides of Ali , Tencent , Baidu on three sides , Three sides Netease , On the one hand, meituan .

Catalog :

1. The Internet 2.Java  Basics & Containers & Sync & Design patterns 3.Java  virtual machine & Memory structure &GC& Class loading & Four quotations & A dynamic proxy 4.Android  Basics & performance optimization &Framwork5.Android  modularization & Hot repair & Hot update & pack & confusion & Compress 6. Audio and video &FFmpeg& player

1、 The Internet

Network protocol model
application layer
: Responsible for handling specific application details HTTP、FTP、DNS

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

The network layer
: Control packet transmission 、 Routing, etc IP

The link layer
: Operating system device driver 、 Network card related interface
TCP  and  UDP  difference
TCP  Connect ; reliable ; Orderly ; Byte stream oriented ; Slow speed ; More weight ; full duplex ; For file transfer 、 The browser etc.

  • full duplex :A  to  B  At the same time as sending the message ,B  Can also give  A  Hair
  • Half duplex :A  to  B  At the same time as sending the message ,B  You can't give  A  Hair

UDP  There is no connection ; unreliable ; disorder ; Message oriented ; Fast ; Light weight ; For instant messaging 、 Video call, etc
TCP  Three handshakes
A: Can you hear ?B: I can hear , Can you hear ?A: I can hear , Let's get started

A  and  B  Both sides should be able to ensure that : What I said , You can hear ; What you said , I can hear . So it takes three handshakes
TCP  Four waves
A: I had said B: I got it! , wait a minute , I may not have finished B: I've finished A: I got it! , It's over

B  received  A  After the end of the message  B  Maybe not yet , Can't immediately reply to the end sign , I can't tell you until you've finished  A : I had said .
POST  and  GET  difference
Get  The parameters are in  url  in ;Post  The parameters are in  request Body  in Get  It may not be safe , Because the parameters are placed in  url  in
HTTPS
HTTP  It's the hypertext transfer protocol , Plaintext transmission ;HTTPS  Use  SSL  Protocol pair  HTTP  The transmission data is encrypted

HTTP  Default  80  port ;HTTPS  Default  443  port

advantage : Security shortcomings : Time consuming 、SSL  Certificate fee , Encryption is still limited , But compared to  HTTP  Much better

2、Java  Basics & Containers & Sync & Design patterns

StringBuilder、StringBuffer、+、String.concat  Link string :
  • StringBuffer  Thread safety ,StringBuilder  Thread unsafe
  • + Actually  StringBuilder  To achieve , So the acyclic can be used directly  +, The circulatory body doesn't work , Because it creates  StringBuilder
  • String.concat  Essence is  new String , It's also inefficient , Time consuming sorting :StringBuilder < StringBuffer < concat < +
Java  Generic erase
  • Generic types related to class structures such as modifying member variables are not erased
  • Container class generics are erased
ArrayList、LinkedList
ArrayList

Based on the array implementation , Quick search :o(1), Add or delete slowly :o(n) The initial capacity is 10, Expansion through  System.arrayCopy  Method

LinkedList

Based on two-way linked list , Search slow :o(n), Additions and deletions quickly :o(1) Encapsulating calls to queues and stacks
HashMap 、HashTable
HashMap

  • Based on array and linked list implementation , An array is  HashMap  The main body of ; Linked lists are used to solve hash conflicts
  • When a hash conflict occurs and the linked list  size  When it is higher than the threshold, it will be expanded ,JAVA 8  It will turn the linked list into a red black tree to improve performance  key/value  by  null

HashTable

  • Data structure and  HashMap  equally
  • Don't allow  value  by  null
  • Thread safety
ArrayMap、SparseArray
ArrayMap

1. Based on two arrays , One store  hash; A storage key value pair . When expanding the capacity, you only need to copy the array , No need to rebuild hash table 2. High memory utilization 3. Not suitable for storing large amounts of data , Because it will be right  key  Do a binary search (1000 following )

SparseArray

1. Based on two arrays ,int  do  key2. High memory utilization 3. Not suitable for storing large amounts of data , Because it will be right  key  Do a binary search (1000 following )
volatile  keyword
  • Can only be used to modify variables , Apply to modify variables that may be accessed by multiple threads at the same time
  • Equivalent to lightweight  synchronized,volatitle  Can guarantee order ( Disable instruction reordering )、 visibility ; The latter also guarantees atomicity
  • Variables are in main memory , Each thread also has its own working memory , The variable has a copy in its own thread's working memory , The thread directly operates on this copy
  • By  volatile  Modified variables are synchronized to main memory immediately after they are changed , Keep the visibility of variables .

Double check singleton , Why add  volatile?

1.volatile The problem to be solved is , You want to use... In another thread instance, Find out instance!=null, But actually instance This problem has not been initialized yet

2. take instance =newInstance(); Split into 3 The sentence is .1. Allocate memory 2. initialization 3. take instance Point to empty allocated memory

3.volatile You can disable reordering of instructions , Make sure you do it first 2, After execution 3
wait  and  sleep
  • sleep  yes  Thread  Static method of , It can be called anywhere
  • wait  yes  Object  Member method of , Only in  synchronized  Call in code block , Otherwise it will be reported  IllegalMonitorStateException  Illegal monitoring status abnormal
  • sleep  The shared resource lock will not be released ,wait  Will release the shared resource lock
lock  and  synchronized
  • synchronized  yes  Java  keyword , Built in features ;Lock  It's an interface
  • synchronized  Will automatically release the lock ;lock  Manual release required , So we need to write  try catch  Block and in  finally  Middle release lock
  • synchronized  Cannot interrupt wait lock ;lock  Interrupts
  • Lock  Can improve multiple threads to read / Efficiency of write operations
  • When the competition for resources is fierce ,lock  Will be significantly better than  synchronized
Reentrant lock
  • Definition : After the lock has been obtained , Call the synchronization block again / You don't have to re apply for a lock when you try to acquire it , Can directly execute the relevant code
  • ReentrantLock  and  synchronized  Are reentrant locks
Fair lock
  • Definition : The thread with the longest waiting time gets the lock first
  • Unfair locks cannot guarantee which thread gets the lock ,synchronized  It's just unfair lock
  • ReentrantLock  By default, the lock is not fair , Can be set to fair lock
Optimistic lock and pessimistic lock
  • Pessimistic locking
    : Once the thread gets the lock , Other threads hang and wait , It is suitable for scenarios with frequent write operations ;synchronized  Is pessimistic lock
  • Optimism lock
    : Suppose there is no conflict , No locks , When updating data, judge whether the data is out of date , If it is overdue, the data will not be updated , It is suitable for scenarios with frequent read operations
  • Optimism lock  CAS
    :Compare And Swap, When updating the data, first compare whether the original values are equal , If it is not equal, it means that the data has been in the past , No data updates
  • Optimistic lock implementation
    :AtomicInteger、AtomicLong、AtomicBoolean
Deadlock  4  Necessary conditions
  • Mutually exclusive
  • To possess and wait for
  • Do not take
  • Loop waiting for
synchronized  principle
  • Each object has a monitor lock :monitor, The synchronization block will execute  monitorenter  Start ,motnitorexit  end
  • wait/notify  Rely on  monitor  The monitor , So executing in an asynchronous code block will report  IllegalMonitorStateException  abnormal

3、Java  virtual machine & Memory structure &GC& Class loading & Four quotations & A dynamic proxy

JVM
  • Definition : It can be understood as a fictional computer , Explain your own bytecode instruction set mapping to local  CPU  or  OS  Set of instructions , The top only needs to focus on  Class  file , It's not about the operating system , Cross platform implementation
  • Kotlin  It can be interpreted as  Class  file , So you can run in  JVM  On
JVM  Memory model
  • Java  Multithreads communicate with each other through shared memory , Each thread has its own local memory
  • Shared variables are stored in main memory , The thread will copy a shared variable to local memory
  • volatile  Keyword is to serve the memory model , To ensure memory visibility and order
JVM  Memory structure
Thread private

1. Program counter : Record the address of the bytecode instruction being executed , If it is being carried out  Native  Method is empty 2. Virtual machine stack : When the method is executed, the data required by the method is saved as a stack frame , After execution, it will be put out of the stack 3. Native Method Stack : Same virtual machine stack , But it's aimed at  Native  Method

Thread sharing

1. Pile up : Storage  Java  example ,GC  The main area , Generational collection  GC  The method will divide the heap into Cenozoic 、 Old age 2. Method area : Store class information , Constant pool , Data such as static variables
GC
Recycling area : Only for heaps 、 Method area ; Thread private area data will be destroyed with the end of the thread , Don't recycle
Recycling type :
1. Objects in the pile

  • Generational collection  GC  The method will divide the heap into Cenozoic 、 Old age
  • The new generation : New small objects will enter the new generation ; Reclaim objects through replication algorithms
  • Old age : New big objects and old ones will enter the old generation ; By marking - Clear algorithm reclaims objects

2. Class information in method area 、 Constant pool
Determine whether an object can be recycled :
1. Disadvantages of reference counting : Circular reference

2. Definition of accessibility analysis : from  GC ROOT  Begin your search , Unreachable objects are recyclable
GC ROOT
1. Virtual machine stack / Objects referenced in the local method stack 2. Constant in method area / Objects referenced by static variables
Four quotations
  • Strong citation : Will not be recycled
  • Soft citation : When there is not enough memory, it will be recycled
  • Weak reference :gc  Will be recycled
  • Virtual reference : Can't get an object through a virtual reference , Can listen for object recycling
ClassLoader
The life cycle of a class :

1. load ;2. verification ;3. Get ready ;4. analysis ;5. initialization ;6. Use ;7. uninstall

Class loading process :

1. load : Gets the binary byte stream of the class ; The runtime storage structure of the generated method area ; Generate... In memory  Class  object 2. verification : Ensure that  Class  The byte stream meets the requirements of the virtual machine 3. Get ready : Initialize static variables 4. analysis : Replace the symbolic reference of the constant pool with a direct reference 5. initialization : Execute static block code 、 Class variable assignment

Class loading time

1. Instantiate objects 2. Calling static methods of a class 3. Call the static variables of the class ( Except for constants put into the constant pool )

Class loader : Responsible for loading  class  file

classification :

1. Boot class loader  -  No parent loader 2. Extended class loader  -  Inherited from bootstrap class loader 3. system class loader  -  Inherited from the extended class loader
Parent commission model :
When you want to load a  class  when , The parent loader will load first layer by layer , If the loading fails, it will load itself

Why are they called parents ? Do not consider custom loaders , The system class loader needs to query two layers on the Internet , So it's called parents

When judging whether it is the same class , Besides information , Must also be the same class loader

advantage :

  • Prevent duplicate loading , The loader is not necessary
  • Security , Prevent tampering with core library classes
Principle and implementation of dynamic agent
  • InvocationHandler  Interface , Dynamic proxy classes need to implement this interface
  • Proxy.newProxyInstance, Used to dynamically create proxy objects
  • Retrofit  application : Retrofit  Through dynamic agents , Generate a dynamic proxy object for each of our defined request interfaces , Implement the request

4、Android  Basics & performance optimization &Framwork

Activity  Boot mode
  • standard  The standard model
  • singleTop  Stack top reuse mode ,
  • Push click message interface
  • singleTask  In stack reuse mode ,
  • home page
  • singleInstance  The singleton pattern , Stand alone in a task stack
  • Call interface details :
  • taskAffinity: Task relevance , Used to specify the task stack name , The default is the application package name
  • allowTaskReparenting: Allow transfer of task stack
View  working principle
  • DecorView (FrameLayout)
  • LinearLayout
  • titlebar
  • Content
  • call  setContentView  Set up  View

ViewRoot  Of  performTraversals  Method call triggers start  View  The draw , And then it calls :

  • performMeasure: Traverse  View  Of  measure  measurement
  • performLayout: Traverse  View  Of  layout  Locate
  • performDraw: Traverse  View  Of  draw  draw
Event distribution mechanism
  • One  MotionEvent  After generation , Press  Activity -> Window -> decorView -> View  Sequential delivery ,View  The delivery process is event distribution , It mainly depends on three methods :
  • dispatchTouchEvent: Used to distribute Events , As long as the click event is received, it will be called , The return result indicates whether the current event has been consumed
  • onInterceptTouchEvent: Used to determine whether to intercept an event , When  ViewGroup  After you're sure you want to intercept the event , The event sequence will no longer trigger the call to this  ViewGroup  Of  onIntercept
  • onTouchEvent: For handling events , The return result indicates whether the current event has been processed , If it is not processed, it will be passed to the parent content  
    《Android Summary of learning notes + Latest mobile architecture video + Big Android interview questions + Project actual combat source code handout 》 Free open source Hui Xin search official account 【 Advanced programming 】
      Processor processing
  • details :
  • An event sequence can only be one  View  Intercept and consume
  • View  No,  onIntercept  Method , Call directly  onTouchEvent  Handle
  • OnTouchListener  Priority ratio  OnTouchEvent  high ,onClickListener  The lowest priority
  • requestDisallowInterceptTouchEvent  You can shield the parent container  onIntercet  Method call
Window 、 WindowManager、WMS、SurfaceFlinger
  • Window
    : Abstract concepts don't exist in reality , But rather  View  There is a form of , adopt  PhoneWindow  Realization
  • WindowManager
    : Outside visits  Window  Entrance , Internal and  WMS  Interaction is a  IPC  The process
  • WMS
    : Manage windows  Surface  The layout and order of , As a system level service, it runs alone in a process
  • SurfaceFlinger
    : take  WMS  The maintenance windows are mixed in a certain order and displayed on the screen
View  Animation 、 Frame animation and attribute animation
View  Animation :

  • The role of targeted  View, You can use  xml  Definition , Suggest  xml  The implementation is easier to read
  • Support four effects : translation 、 The zoom 、 rotate 、 transparency

Frame animation :

  • adopt  AnimationDrawable  Realization , Easy to  OOM

Attribute animation :

  • It works on any object , You can use  xml  Definition ,Android 3  introduce , It is suggested that the code implementation is more flexible
  • Include  ObjectAnimator、ValuetAnimator、AnimatorSet
  • Time interpolator : Calculates the percentage of the current property change based on the percentage of time elapsed
  • System preset constant speed 、 Speed up 、 Interpolators such as deceleration
  • Type estimator : Calculate the changed attribute value according to the percentage of current attribute change
  • System preset integer 、 floating-point 、 Color value and other types of estimators
  • Precautions for use :
  • Avoid frame animation , Easy to OOM
  • Stop animation when the interface is destroyed , Avoid memory leaks
  • Turn on hardware acceleration , Improve animation fluency  , Hardware acceleration :
  • take  cpu  Part of the work is shared with  gpu , Use  gpu  Finish drawing
  • The rendering speed is optimized from two aspects of work sharing and rendering mechanism
Handler、MessageQueue、Looper
  • Handler: Develop direct contact classes , Internal holding  MessageQueue  and  Looper
  • MessageQueue: Message queue , Internal storage of messages through a single linked list
  • Looper: Internal holding  MessageQueue, Loop through to see if there's new news , Deal with it if you have , It's blocked if it doesn't
  • How to achieve blocking : adopt  nativePollOnce  Method , be based on  Linux epoll  Event management mechanism
  • Why doesn't the main thread because  Looper  Blocking : Every time the system  16ms  Will send a refresh  UI  Wake up the news
MVC、MVP、MVVM
  • MVP:Model: Processing data ;View: Control view ;Presenter: Separate  Activity  and  Model
  • MVVM:Model: Process, get, save data ;View: Control view ;ViewModel: Data container
  • Use  Jetpack  Component architecture  LiveData、ViewModel  Convenient implementation  MVVM
Serializable、Parcelable
  • Serializable :Java  Serialization mode , Suitable for storage and network transmission ,serialVersionUID  Used to determine whether the deserialization and class versions are consistent , Deserialization failed when inconsistent
  • Parcelable :Android  Serialization mode , It is suitable for component communication data transmission , High performance , Because they don't like  Serializable  There are also a lot of reflection operations , frequent  GC
Binder
  • Android  The mainstay of interprocess communication , client-based - Server communication mode
  • Use  mmap  One copy of data to achieve  IPC, Tradition  IPC: user A Space -> kernel -> user B Space ;mmap  The kernel and the user B Spatial mapping , Directly from the user A Space -> user B Space
  • BinderPool  Avoid creating multiple  Service
IPC  The way
  • Intent extras、Bundle: Request that the pass data be serialized , Realization  Parcelable、Serializable , It is suitable for communication of four components
  • File sharing : It is suitable for simple data exchange scenarios with low real-time performance
  • AIDL:AIDL  The interface is essentially provided by the system and can be implemented easily  BInder  Tools for
  • Android Interface Definition Language, The method can be called across processes
  • Server side : Declare the interface exposed to the client in  AIDL  In file , establish  Service  Realization  AIDL  Interface and listen for client connection requests
  • client : Binding server  Service , After successful binding, get the server  Binder  Object to  AIDL  Interface call
  • RemoteCallbackList  Implement cross process interface monitoring , Same  Binder  Object to do  key  Store client registered  listener
  • monitor  Binder  To break off :1.Binder.linkToDeath  Set up death agent ;2. onServiceDisconnected  Callback
  • Messenger: be based on  AIDL  Realization , Server side serial processing , It is mainly used to deliver messages , It is suitable for low concurrency one to many communication
  • ContentProvider: be based on  Binder  Realization , It is suitable for data sharing among one to many processes
  • Socket:TCP、UDP, For data exchange over the Internet
Android  System startup process
  • Press the power button  ->  Load bootloader  BootLoader  To  RAM ->  perform  BootLoader  Program boot kernel  ->  start-up  init  process  ->  start-up  Zygote  And various daemons  ->
  • start-up  System Server  The service process starts  AMS、WMS  etc.  ->  start-up  Launcher  Application process
App  Start process
Launcher  Click an application icon in the  ->  adopt  AMS  Find the application process , If it doesn't exist, through  Zygote  process  fork
Process keeping alive
  • Process priority :1. Foreground process  ;2. See the process ;3. Service process ;4. Background processes ;5. Empty process
  • The process is  kill  scene :1. Cut to the background memory is not enough to be killed ;2. Cut to the backstage manufacturer, save the motor system and kill ;3. Users take the initiative to clean up
  • How to keep alive :
  • 1.Activity  Raise the right : Hang one  1 Pixels  Activity  Raise the process priority to the foreground process
  • 2.Service  Raise the right : Start a front desk service (API>18 There will be a running notification bar )
  • 3. Radio pull live
  • 4.Service  Pull up
  • 5.JobScheduler  Regular tasks make life
  • 6. Two processes to bring life to
Network optimization and detection
  • Speed :1.GZIP  Compress (okhttp  Automatic support );2.Protocol Buffer  replace  json;3. Optimize pictures / File traffic ;4.IP  Direct connection saves  DNS  Parsing time
  • The success rate :1. Failed retry strategy ;
  • Traffic :1.GZIP  Compress (okhttp  Automatic support );2.Protocol Buffer  replace  json;3. Optimize pictures / File traffic ;5. File download breakpoint resume  ;6. cache
  • Optimization of protocol layer , For example, better  http  Version, etc
  • monitor :Charles  Grab the bag 、Network Monitor  Monitor traffic
UI Carton optimization
  • Reduce layout level and control complexity , Avoid over drawing
  • Use  include、merge、viewstub
  • Optimize the rendering process , To avoid the  Draw  Create objects frequently in 、 Do time-consuming operations
Memory leak scenarios and avoidance
1. Static variables 、 Singleton strongly refers to data or resources related to the life cycle , Include  EventBus2. The cursor 、IO  Flow and other resources forget to release actively 3. Interface related animation will be suspended in time when the interface is destroyed 4. Internal classes hold memory leaks caused by external class references

  • handler  Internal class memory leak avoidance :1. Use static inner classes + Weak reference  2. Clear the message queue when the interface is destroyed
  • testing :Android Studio Profiler
LeakCanary  principle
  • Monitor whether the object is recycled through weak reference and reference queue
  • such as  Activity  Start monitoring this object when it is destroyed , If it is detected that it has not been recycled, it will take the initiative to  gc , And then continue to monitor
OOM  Scene and avoidance
  • Load large : Reduce the image
  • Memory leak : Avoid memory leaks

5、Android  modularization & Hot repair & Hot update & pack & confusion & Compress

Dalvik  and  ART
  • Dalvik
  • Google design is dedicated to  Android  Platform  Java  virtual machine , Direct operation  .dex  file , Suitable for systems with limited memory and processing speed
  • JVM  The instruction set is stack based ;Dalvik  The instruction set is based on registers , Code execution efficiency is better
  • ART
  • Dalvik  Every run converts bytecode to machine code ;ART  It will be converted to machine code when the application is installed , Faster execution
  • ART  It takes more space to store machine code , Space for time
APK  Packaging process
1.aapt  Package resource file generation  R.java  file ;aidl  Generate  java  file 2. take  java  The file is compiled as  class  file 3. Connect the project with the third party's  class  File conversion to  dex  file 4. take  dex  file 、so、 Compiled resources 、 The original resources are packed into  apk  file 5. Signature 6. Resource file alignment , Reduce runtime memory
App  setup script
  • First of all, decompress  APK, resources 、so Put it in the app directory
  • Dalvik  Will  dex  Processing into  ODEX ;ART  Will  dex  Processing into  OAT;
  • OAT  contain  dex  And machine code compiled at installation time
Component based routing implementation
ARoute: adopt  APT  analysis  @Route  Etc , combination  JavaPoet  Generate routing table , Routing and  Activity  The mapping relation of

6、 Audio and video &FFmpeg& player

FFmpeg
Based on the command mode to achieve an audio and video editing  App

The integration compiles  AAC、MP3、H264  Encoder
Player principle
The principle of video playing :(mp4、flv)->  decapsulation  -> (mp3/aac、h264/h265)->  decode  -> (pcm、yuv)->  Audio video synchronization  ->  Render play

Audio video synchronization :

  • Select reference clock source : Audio time stamp 、 Choose one of the video time stamp and external time as the reference clock source ( Generally choose audio , Because people are more sensitive to audio ,ijk  The default is also audio )
  • Align the video stream with the reference clock source by waiting or dropping frames , Synchronization
IjkPlayer  principle
Integrated  MediaPlayer、ExoPlayer  and  IjkPlayer  Three realizations , among  IjkPlayer  be based on  FFmpeg  Of  ffplay

Audio output mode :AudioTrack、OpenSL ES; Video output mode :NativeWindow、OpenGL ES

【 extend Android Essential knowledge 】

null
【Android Some advanced architecture video learning resources 】

**Android It is even more powerful after intensive video learning !** March BATJ Big factory, etc ( Prepare for war )! Now it's said that the Internet winter , It's just that you got on the wrong car , And wear less ( Skill ), If you get on the right car , I have strong technical ability , The cost of replacing the company is high , How could it be cut off , It's all about eliminating the end of the business Curd nothing more ! Nowadays, there are a lot of junior programmers in the market , This tutorial is for Android Development Engineer 1-6 People in 、 It's in a bottleneck period , I want to break through my salary increase in the next year , Advanced Android Middle and advanced 、 The architect is more like a fish in water for you !

** Any market is survival of the fittest , As long as you are skilled , There is no problem of saturation anywhere , So it's important to improve yourself . Know more is your bonus   Not required . The high threshold only proves that the market is maturing !** A thousand other readers have a thousand Hamlets , So that's the key , No joy, no spray. !

If you are stuck in the bottleneck of lack of learning resources , So it's just right. I can help you . Welcome to continue to update and share .
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051909475540.html