当前位置:网站首页>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
Catalog :
1、 The Internet
Network protocol model
TCP and UDP difference
- 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
TCP Three handshakes
TCP Four waves
POST and GET difference
HTTPS
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
HashMap 、HashTable
- 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
- Data structure and HashMap equally
- Don't allow value by null
- Thread safety
ArrayMap、SparseArray
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 .
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
GC
Recycling type :
- 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
Determine whether an object can be recycled :
GC ROOT
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
Parent commission model :
- 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
- 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
- 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
- adopt AnimationDrawable Realization , Easy to OOM
- 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
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
- 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
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
6、 Audio and video &FFmpeg& player
FFmpeg
Player principle
- 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
边栏推荐
- 建议收藏,我的腾讯Android面试经历分享
- Common - Hero Minesweeper
- Hiengine: comparable to the local cloud native memory database engine
- Mariadb root用户及普通用户的密码 重置
- How to choose the notion productivity tools? Comparison and evaluation of notion, flowus and WOLAI
- [hard core dry goods] which company is better in data analysis? Choose pandas or SQL
- 【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
- 【硬核干货】数据分析哪家强?选Pandas还是选SQL
- Do you know several assertion methods commonly used by JMeter?
- Vagrant2.2.6 supports virtualbox6.1
猜你喜欢
集合
Force buckle 729 My schedule I
Fuzor 2020 software installation package download and installation tutorial
安卓面试宝典,2022Android面试笔试总结
PHP利用ueditor实现上传图片添加水印
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
Two pits exported using easyexcel template (map empty data columns are disordered and nested objects are not supported)
MMO項目學習一:預熱
Microwave radar induction module technology, real-time intelligent detection of human existence, static micro motion and static perception
【C语言】字符串函数及模拟实现strlen&&strcpy&&strcat&&strcmp
随机推荐
Summer Challenge database Xueba notes, quick review of exams / interviews~
Debezium系列之:解析默认值字符集
Reflection and imagination on the notation like tool
大厂面试必备技能,2022Android不死我不倒
Android面试,android音视频开发
城链科技数字化创新战略峰会圆满召开
[AI framework basic technology] automatic derivation mechanism (autograd)
多分支结构
国海证券在网上开户安全吗?
Webuploader file upload drag upload progress monitoring type control upload result monitoring control
手机开户选择哪家券商公司比较好哪家平台更安全
再忙不能忘安全
S7-200SMART利用V90 MODBUS通信控制库控制V90伺服的具体方法和步骤
Force buckle 729 My schedule I
The difference between ID selector and class selector
【obs】libobs-winrt :CreateDispatcherQueueController
全网最全的低代码/无代码平台盘点:简道云、伙伴云、明道云、轻流、速融云、集简云、Treelab、钉钉·宜搭、腾讯云·微搭、智能云·爱速搭、百数云
IBM大面积辞退40岁+的员工,掌握这十个搜索技巧让你的工作效率至上提高十倍
函数的概念及语法
Xaas trap: all things serve (possible) is not what it really needs