当前位置:网站首页>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
边栏推荐
- Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL
- openh264解码数据流向分析
- 【obs】libobs-winrt :CreateDispatcherQueueController
- C application interface development foundation - form control (6) - menu bar, toolbar and status bar controls
- 【C语言】字符串函数及模拟实现strlen&&strcpy&&strcat&&strcmp
- What do software test engineers do? How about the prospect of treatment?
- Fundamentals of shell programming (Part 8: branch statements -case in)
- XaaS 陷阱:万物皆服务(可能)并不是IT真正需要的东西
- 微波雷达感应模块技术,实时智能检测人体存在,静止微小动静感知
- Hiengine: comparable to the local cloud native memory database engine
猜你喜欢
HiEngine:可媲美本地的云原生内存数据库引擎
HiEngine:可媲美本地的云原生内存数据库引擎
How MySQL queries and modifies JSON data
四万字长文说operator new & operator delete
UWB ultra wideband positioning technology, real-time centimeter level high-precision positioning application, ultra wideband transmission technology
aggregate
城链科技数字化创新战略峰会圆满召开
【无标题】
Fuzor 2020軟件安裝包下載及安裝教程
webuploader文件上传 拖拽上传 进度监听 类型控制 上传结果监听控件
随机推荐
JAD的安装、配置及集成IDEA
毫米波雷达人体感应器,智能感知静止存在,人体存在检测应用
使用easyexcel模板导出的两个坑(Map空数据列错乱和不支持嵌套对象)
成功入职百度月薪35K,2022Android开发面试解答
Fuzor 2020 software installation package download and installation tutorial
Decision tree and random forest
MySql中的longtext字段的返回问题及解决
Concept and syntax of function
40000 word Wenshuo operator new & operator delete
四万字长文说operator new & operator delete
【无标题】
Inventory of the most complete low code / no code platforms in the whole network: Jiandao cloud, partner cloud, Mingdao cloud, Qingliu, xurong cloud, Jijian cloud, treelab, nailing · Yida, Tencent clo
2022 the latest big company Android interview real problem analysis, Android development will be able to technology
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
How to apply smart contracts more wisely in 2022?
Apprentissage du projet MMO I: préchauffage
Fundamentals of shell programming (Part 8: branch statements -case in)
HiEngine:可媲美本地的云原生内存数据库引擎
Django使用mysqlclient服务连接并写入数据库的操作过程
信息/数据