当前位置:网站首页>Android: answers to the recruitment and interview of intermediate Android Development Agency in early 2019 (medium)

Android: answers to the recruitment and interview of intermediate Android Development Agency in early 2019 (medium)

2022-04-23 13:56:00 InfoQ

 *  advantage : Any task will be performed immediately ( Task queue SynchronousQuue It's equivalent to an empty set ); It's better to perform a lot of less time-consuming tasks .
 * **newFixedThreadPool**: Only the core thread , And a fixed number of , When all threads are active , Because the size of the queue is not limited , New tasks will be waiting to be performed , Worker threads are not released when the thread pool is idle , It will also occupy certain system resources .
 *  advantage : Faster response to external requests
 * **newScheduledThreadPool**: The number of core threads is fixed , Non core thread ( Idle work will be recycled immediately ) There is no limit to .
 *  advantage : Perform scheduled tasks and repetitive tasks with fixed cycles
 * **newSingleThreadExecutor**: There is only one core thread , Make sure that all tasks are done in the same thread in sequence
 *  advantage : There's no need to deal with thread synchronization
*  Through the source code, we can know that the above four thread pools are actually used  ThreadPoolExecutor  Class implements the
 
 ![](https://user-gold-cdn.xitu.io/2019/3/14/1697b39705b3f2e3?imageView2/0/w/1280/h/960/ignore-error/1)
  • Recommended articles :[java Thread pool parsing and the use of four thread pools ](()
2、Android We also know which classes are convenient for thread switching ?
  • Reference answer :
  • AsyncTask
    : The bottom layer encapsulates the thread pool and Handler, Easy to perform background tasks and in sub threads UI operation .
  • HandlerThread
    : A thread with a message loop , It can be used inside Handler.
  • IntentService
    : It's asynchronous 、 Automatically stopped services , Internal use HandlerThread.
3、 Tell me about AsyncTask Principle
  • Reference answer :
  • AsyncTask There are two thread pools in (SerialExecutor and THREAD_POOL_EXECUTOR) And a Handler(InternalHandler), Where thread pool SerialExecutor Queuing for tasks , And the thread pool THREAD_POOL_EXECUTOR Used to actually perform tasks ,InternalHandler Used to switch execution environment from thread pool to main thread .
  • sHandler It's a static Handler object , In order to be able to switch the execution environment to the main thread , This requires that sHandler This object must be created in the main thread . Because static members are initialized when the class is loaded , So this is a disguised requirement AsyncTask Must be loaded in the main thread , Otherwise, in the same process AsyncTask Will not work properly .
4、IntentService What's the usage?  ?
  • Reference answer :
  • IntentService
    Can be used for
    It takes time to execute the background
    The task of , When the task is completed
    Auto stop
    , At the same time as IntentService It's the service , Different from ordinary Service,IntentService can
    Automatically create child threads
    To perform the task , This leads to a higher priority than a single thread , Not easily killed by the system , therefore IntentService It is more suitable to perform some
    High priority
    Background tasks for .
5、 Directly in Activity Create a thread With the service Create a thread The difference between ?
  • Reference answer :
  • stay Activity Is created in
    : The Thread That's why Activity Service , Complete this particular Activity The task assigned , Take the initiative to inform the Activity Some news and events ,Activity After destruction , The Thread There's no point in living .
  • stay Service Is created in
    : This is to guarantee the longest life cycle Thread The only way , As long as the whole Service Do not exit ,Thread It can be executed in the background all the time , Generally in Service Of onCreate() Created in , stay onDestroy() Medium destruction . therefore , stay Service Created in the Thread, Suitable for long-term execution some independent of APP Background tasks for , The common one is : stay Service Keep a long connection with the server side .
6、ThreadPoolExecutor The working strategy of  ?
  • Reference answer :ThreadPoolExecutor The following rules will be followed when performing tasks
  • If the number of threads in the thread pool
    Not up to
    Number of core threads , Then a core thread will be started directly to execute the task .
  • If the number of threads in the thread pool
    Already achieved
    Or more than the number of core threads , Then the task will be inserted into the task queue to wait for execution .
  • If in the first place 2 Point cannot insert task into task queue , This is often because the task queue is full , At this time, if the number of threads
    The maximum value specified by thread pool is not reached
    , A non core thread will be started immediately to execute the task .
  • If the first 3 Number of threads in the point
    The maximum value specified by thread pool has been reached
    , Then refuse to perform this task ,ThreadPoolExecutor Would call RejectedExecutionHandler Of rejectedExecution Method to notify the caller .
7、Handler、Thread and HandlerThread The difference between ?
  • Reference answer :
  • Handler
    : stay android Responsible for sending and processing messages in , It can realize message communication between other branch threads and main threads .
  • Thread
    :Java The smallest unit of operation performed in the process , That is, the basic unit of executing processor scheduling . A program that runs alone in a process .
  • HandlerThread
    : One is inherited from Thread Class HandlerThread,Android There is no right in Java Medium Thread Carry out any encapsulation , Instead, it provides an inheritance from Thread Class HandlerThread class , This class is right Java Of Thread Made a lot of convenient packaging .HandlerThread Inherited from Thread, So its essence is a Thread. And ordinary Thread The difference is , It's implemented directly inside Looper The implementation of the , This is a Handler Message mechanism is essential . Have your own looper, It allows us to distribute and process messages in our own threads . If not HandlerThread Words , It needs to be called manually Looper.prepare() and Looper.loop() These methods .
8、ThreadLocal Principle
  • Reference answer :
  • ThreadLocal Is a class about creating thread local variables . The usage scenario is as follows :
  • The implementation of single thread single instance and single thread context information storage , Like trading id etc. .
  • Achieve thread safety , Non thread safe object use ThreadLocal Then it becomes thread safe , Because each thread will have a corresponding instance .  Carry some thread related data , Avoid passing parameters back and forth in methods .
  • When multithreading is needed , There's a variable that happens not to need to be shared , You don't have to use synchronized Such a troublesome keyword to lock , Each thread is equivalent to opening up a space in heap memory , The thread has a buffer for shared variables , Read and operate the shared variables in the heap memory through the buffer ,ThreadLocal Equivalent to the memory in the thread , A local variable . It can read and operate the thread's own data every time , There is no need to go through the buffer with   Variables in main memory interact . It's not like synchronized Modify the main memory data in that way , Then copy the data from the main memory to the working memory in the thread .ThreadLocal The thread can have exclusive resources , Stored inside the thread , Avoid thread blocking CPU Throughput decrease .
  • At every Thread Contains a ThreadLocalMap,ThreadLocalMap Of key yes ThreadLocal The object of ,value It's exclusive data .
9、 Will multithreading be efficient ( Advantages and disadvantages )
  • Reference answer :
  • Advantages of multithreading :
  • Convenient and efficient memory sharing  -  It's inconvenient to share memory in multiple processes , And it will cancel out the benefits of multiprocess programming
  • Lighter context switching overhead  -  No need to switch address space , Don't change CR3 register , No emptying TLB
  • The task on the thread is automatically destroyed after execution
  • The disadvantage of multithreading :
  • Starting a thread requires a certain amount of memory space ( By default , Every thread takes up 512KB)
  • If you start a lot of threads , It takes up a lot of memory space , Reduce the performance of the program
  • More threads ,cpu The higher the overhead on the calling thread
  • Programming is more complicated , For example, communication between threads 、 Multithreaded data sharing
  • To sum up, it can be concluded that , Multithreading
    not always
    It can improve efficiency , When the memory space is tight, it is a kind of burden , So in daily development , Try to
  • Don't create... Frequently , Destruction of the thread , Use thread pool
  • Reduce synchronization and communication between threads ( Most of all )
  • Avoid the need for frequent sharing of written data
  • Reasonably arrange the shared data structure , Avoid pseudo sharing (false sharing)
  • Use non blocking data structures / Algorithm
  • Avoid system calls that can cause scalability problems ( such as mmap)
  • Avoid a lot of page missing exceptions , Use as much as possible Huge Page
  • Use user light threads instead of kernel threads if possible
10、 In a multithreaded , Let's make a single example , What would you do
  • Reference answer :
  • There are many factors to consider in establishing singleton mode in multithreading , For example, thread safety  - Delay loading - code safety : Such as preventing serialization attacks , Prevent reflex attacks ( Prevent reflection from making private method calls ) - Performance factors
  • There are many ways to do this , The hungry , lazy ( Thread safety , Thread is not safe ), Double check (DCL), Inner class , And enumeration
  • null
  • Recommended articles :[ Summary of the singleton pattern ](()
11、 except notify What else can I do to wake up threads
  • Reference answer :
  • When one has Object Lock thread call  wait() When the method is used , Will cause the current thread to join object.wait  Waiting in the queue , And release the currently occupied Object lock , So that other threads have a chance to get this Object lock , get Object Lock thread call notify() Method , You can be in Object.wait  Wait for a thread to wake up randomly in the queue ( The wake-up is random and has nothing to do with the order in which it is added , The higher the priority, the higher the wakeup probability )
  • If the notifyAll() Method to wake up all threads .
    Be careful : call notify() Method does not immediately release object lock , Will wait for the thread to finish executing before releasing Object lock .
12、 What is? ANR ?  What will happen ANR ? How to avoid  ?  How to quickly locate and appear without looking at the code ANR The problem  ?
  • Reference answer :
  • ANR(Application Not Responding, No response from application ): When an operation cannot be processed by the system for a period of time , It will pop up at the system level ANR Dialog box
  • produce ANR Probably because 5s No response to user input events 、10s It's not over BroadcastReceiver、20s It's not over Service
  • Want to avoid ANR Don't do time-consuming operations on the main thread , But by opening a child thread , Methods like inheritance Thread Or implementation Runnable Interface 、 Use AsyncTask、IntentService、HandlerThread etc.
  • Recommended articles :[ How to quickly analyze and locate ANR](()

Bitmap

1、Bitmap What problems should be paid attention to when using  ?
  • Reference answer :
  • Choose the right picture size (bitmap type )
    : Usually we optimize Bitmap when , When performance optimization or prevention is needed OOM, We usually use them RGB_565, because ALPHA_8 Transparency only , It doesn't make sense to show general pictures ,Bitmap.Config.ARGB_4444 The display picture is not clear ,Bitmap.Config.ARGB_8888 Most memory occupied .:
  • ALPHA_8  Each pixel occupies 1byte Memory
  • ARGB_4444  Each pixel occupies 2byte Memory
  • ARGB_8888  Each pixel occupies 4byte Memory ( Default )
  • RGB_565  Each pixel occupies 2byte Memory
  • Reduce sampling rate
    :BitmapFactory.Options  Parameters inSampleSize Use , The first options.inJustDecodeBounds Set to true, Just read the size of the picture , After getting the size of the picture, compare it with the size to be displayed calculateInSampleSize() Function calculation inSampleSize The specific value of , After getting the value .options.inJustDecodeBounds Set to false Read picture resources .
  • Reuse memory
    : That is, through soft reference ( Only when there is not enough memory will it be recycled ), Reuse memory blocks , There's no need to give this again bitmap Apply for a new piece of memory , Avoid one-time memory allocation and recycling , Thus, the operation efficiency is improved .
  • Use recycle() Methods reclaim memory in time
    .
  • The compressed image
    .
2、Bitmap.recycle() Will it be recycled immediately ? When will it be recycled ? If there is no place to use this Bitmap, Why garbage collection doesn't recycle directly ?
  • Reference answer :
  • You can learn from the source code , load Bitmap When it's in memory , Is included
    Two parts of memory area
    Of . To put it simply , Part of it is
    Java part
    Of , Part of it is
    C part
    Of . This Bitmap The object is Java Partially allocated , When not in use, the system will automatically recycle
  • But that corresponds to
    C You can use
    The memory area of , Virtual machines cannot be recycled directly , This can only call the underlying function to release . So you need to call recycle() Method to release C Part of the memory
  • bitmap.recycle() Method is used to recover the Bitmap Memory used , And then bitmap empty , Finally using System.gc() Call the garbage collector of the system to recycle , call System.gc() There is no guarantee that the recycling process will begin immediately , But just to speed up the arrival of recycling .
3、 a sheet Bitmap The memory occupied and the calculation of the memory occupied
  • Reference answer :
  • Bitamp  Memory footprint  =  Width pixels  x (inTargetDensity / inDensity) x  Height pixel  x (inTargetDensity / inDensity)x  The size of memory bytes occupied by a pixel
  • notes : here inDensity That represents the target image dpi( In which resource folder ),inTargetDensity That represents the target screen dpi, So you can find inDensity and inTargetDensity Would be right Bitmap Stretch the width and height of , And then change Bitmap The size of the occupied memory .
  • stay Bitmap There are two ways to get the memory footprint in .
  • getByteCount()
    :API12  Join in , Representative storage  Bitmap  Minimum memory required for pixels .
  • getAllocationByteCount()
    :API19  Join in , Represents in memory as  Bitmap  Allocated memory size , Instead of  getByteCount()  Method .
  • stay
    Do not reuse  Bitmap
      when ,getByteCount()  and  getAllocationByteCount  The result is the same . Through
    Reuse  Bitmap
      When decoding pictures , that  getByteCount()  Indicates the amount of memory occupied by the newly decoded picture   Small ,getAllocationByteCount()  Indicates that it is reused  Bitmap  The actual amount of memory used
4、Android Cache update strategy in  ?
  • Reference answer :
  • Android Cache update policy for
    There is no uniform standard
    , Generally speaking , The cache strategy mainly includes
    Add cache 、 Get and delete
    These three types of operations , But whether it's memory cache or storage device cache , Their cache capacity is limited , So delete some old caches and add new caches , How to define the old and new cache is a strategy ,
    Different strategies correspond to different caching algorithms
  • For example, you can simply define the new and old of the cache according to the last modification time of the file , When the cache is full, the cache that was last modified earlier is removed , This is a caching algorithm , But it's not perfect
5、LRU Principle  ?
  • Reference answer :
  • In order to reduce flow consumption , Caching strategy can be adopted . The commonly used caching algorithm is LRU(Least Recently Used): When the cache is full ,  Will give priority to those cache objects that have been used least recently . There are mainly two ways :
  • LruCache( Memory cache )
    :LruCache Class is a thread safe generic class : An internal LinkedHashMap Store external cache objects by strong reference , And provide get and put Method to get and add the cache , When the cache is full, older cache objects are removed , Add a new cache object .
  • DiskLruCache( Disk caching )
    :  The cache effect is achieved by writing cache objects to the file system

performance optimization

1、 In the third level cache of pictures , Pictures are loaded into memory , If the memory is going to burst , What's going to happen ? How to deal with ?
  • Reference answer :
  • First of all, we need to know how the three-level cache of images
  • null
  • If there is enough memory, do not recycle . Reclaim soft reference objects when there is not enough memory
2、 If you load one in memory 500*500 Of png HD picture . How much memory should it take ?
  • Reference answer :
  • Regardless of the screen ratio
    : Take up memory =500 * 500 * 4 = 1000000B ≈ 0.95MB
  • Considering the screen ratio
    : Take up memory =  Width pixels  x (inTargetDensity / inDensity) x  Height pixel  x (inTargetDensity / inDensity)x  The size of memory bytes occupied by a pixel
  • inDensity That represents the target image dpi( In which resource folder ),inTargetDensity That represents the target screen dpi
  • null
3、WebView Performance optimization  ?
  • Reference answer :
  • In the process of loading a web page ,native、 The Internet 、 The back-end processing 、CPU Will participate in , Each has the necessary work and dependency ; Let them work in parallel with each other instead of blocking each other to make web pages load faster :
  • WebView Slow initialization , You can request data at the same time of initialization , Let the back end and network not be idle .
  • Commonly used  JS  Localization and delayed loading , Use a third party to browse the kernel
  • Slow back end processing , You can let the server share trunk Output , At the same time of back-end computing, the front-end also loads static network resources .
  • Slow script execution , Just let the script run at the end , Does not block page parsing .
  • meanwhile , Reasonable preloading 、 Pre caching can make the load speed bottleneck smaller .
  • WebView Slow initialization , Just initialize one at any time WebView To be used .
  • DNS And links are slow , Try to reuse the domain names and links used by clients .
  • null
  • Recommended articles :[WebView performance 、 Experience analysis and optimization ](()
4、Bitmap How to deal with the big picture , Like a picture 30M Big picture of , How to prevent OOM?
  • Reference answer : avoid OOM We need to manage the loading of large images , Mainly through zooming to reduce the memory consumption of the picture .
  • BitmapFactory There are four ways to load images (
    decodeFile、decodeResource、decodeStream、decodeByteArray
    ) All support BitmapFactory.Options Parameters , adopt inSampleSize Parameters can easily sample and scale an image
  • Such as a 1024_1024 For HD pictures . So the memory it occupies is 1024_1024_4, namely 4MB, If inSampleSize by 2, Then the sampled images only occupy memory 512_512*4, namely 1MB(
    Be careful : According to the latest official documents ,inSampleSize The value of should always be 2 The index of , namely 1、2、4、8 wait , If the external input is insufficient 2 The index of , The system will also default to select the closest 2 Instead of , such as 2
  • Comprehensive consideration . The image can be loaded effectively through the sampling rate , The process is as follows
  • take BitmapFactory.Options Of inJustDecodeBounds The parameter is set to true And load the picture
  • from BitmapFactory.Options Take out the original width and height information of the picture , They correspond to outWidth and outHeight Parameters
  • According to the rules of sampling rate and the target View To calculate the sample rate inSampleSize
  • take BitmapFactory.Options Of inJustDecodeBounds The parameter is set to false, Reload image
  • null
  • Recommended articles :[Android Load large images efficiently 、 Multi graph solutions , Effective avoidance procedures OOM](()
5、 Memory recovery mechanism and GC Algorithm ( Advantages and disadvantages of various algorithms and application scenarios );GC Principle, timing and GC object
  • Reference answer :
  • There are two mechanisms for determining that memory objects can be reclaimed :
  • Reference counting algorithm
    : Add a reference counter to the object , Whenever there's a place to quote it , The counter value adds 1; When the reference fails , The counter value is reduced 1; The counter at any time is 0 It is impossible to use the object of . But in the mainstream Java The reference counting algorithm is not selected in the virtual machine to manage memory , The main reason is that it is difficult to solve the problem between objects
    Circular reference to each other
    The problem of , So there is another object survival decision algorithm .
  • Accessibility analysis
    : Through a series called 『GCRoots』 As the starting point , Start with these nodes and drill down , The search path is called _
    References to the chain
    , When an object arrives GC Roots When no chain of references is connected , Then prove that this object is not available . Which can be used as GC Roots The object of : Objects referenced in the virtual machine stack , It mainly refers to... In stack frame __ The local variable _*、 Local method stack
    Native
    Method reference object 、 Method area
    Class static
    Property reference object 、 Method area
    Constant
    Referenced object
  • GC There are four recycling algorithms :
  • Generational collection algorithm
    : It is an algorithm used by commercial virtual machines at present , Depending on the life cycle of the object , take Java Heaps are divided into new and old generations , According to the characteristics of each age, the most appropriate collection algorithm is adopted .
  • The new generation : A lot of people die , Only a few survive . Use 『 Copy algorithm 』, Just copy a few surviving objects .
  • Copy algorithm
    : Divide the available memory into two equal sized blocks according to its capacity , Use only one piece at a time . When this block of memory runs out , Put the living objects 『 Copy 』 Go to another piece , Clean up this memory space again .
    Implement a simple , Efficient operation . When the survival rate of objects is high, more replication operations are needed , Efficiency will be lower
  • Old age : The survival rate is high . Use 『 Mark — Clean up algorithm 』 perhaps 『 Mark — Sorting algorithm 』, Just mark fewer recycled objects .
  • Mark - Clear algorithm
    : First 『 Mark 』 All objects that need to be recycled , And then unify 『 eliminate 』 All marked objects .
    The efficiency of both marking and clearing processes is not high , After clearing, a large number of discontinuous memory fragments will be generated , Too much space debris may lead to the need to allocate large objects in the process of program running later , Unable to find enough contiguous memory to trigger another garbage collection action in advance .
  • Mark - Sorting algorithm
    : First 『 Mark 』 All objects that need to be recycled , Then proceed 『 Arrangement 』, Make all living objects move to one end , Finally, clean up the memory outside the end boundary .
    The tag collation algorithm moves all living objects to one end , And deal with objects that don't survive , So it doesn't produce memory fragmentation
  • Recommended articles :[ The illustration Java  Garbage collection mechanism ](()
6、 The difference between memory overflow and memory leak  ?AS What tools are available to detect memory leaks
  • Reference answer :
  • out of memory (out of memory)
    : When a program requests memory , Not enough memory for it , appear out of memory; Like applying for a integer, But save it long Number that can be saved , That's memory overflow .
  • Memory leak (memory leak)
    : Refers to the program after applying for memory , Unable to free requested memory space , The harm of a memory leak can be ignored , But the memory leak has serious consequences , No matter how much memory , Sooner or later it will be taken up .
    memory leak Will eventually lead to out of memory!
  • To find memory leaks, you can use Android Studio  Self contained
    AndroidProfiler
    Tools or
    MAT
7、 performance optimization , How to make sure that the app doesn't get stuck when it starts ?  How to deal with black and white screen ?
  • Reference answer :
  • Application startup speed
    , It depends on what you are doing application What did you do inside , For example, you integrate a lot of sdk, also sdk Of init All operations need to be implemented in the main thread, so there will be a feeling of Caton . If not necessary, you can delay loading or start sub thread processing
  • in addition , influence
    Interface stuck
    Two major factors , Namely
    Interface drawing and data processing .
  • Layout optimization ( Use include,merge label , Complex layouts are recommended ConstraintLayout etc. )
  • onCreate()  Time consuming operations are not performed in   Show the page  View  Break it down , Put it in  AsyncTask  It's gradually shown , use  Handler  Better . In this way, users can see one by one in a hierarchical and step-by-step way  View  The exhibition of , You don't see a black screen first , And then I'll show you all  View. It's better to make animation , The effect is more natural .
  • The purpose of multithreading is to minimize  onCreate()  and  onReume()  Time for , So that users can see the page as soon as possible , Operation page .
  • Reduce the main thread blocking time .
  • Improve  Adapter  and  AdapterView  The efficiency of .
  • Recommended articles :[Android  Memory detection for performance optimization 、 Carton optimization 、 Power consumption optimization 、APK Slimming ](()
  • Black and white screen causes
    : When we start an app , The system will check whether such a process already exists , If it doesn't exist , The service of the system will check startActivity Medium intent Information about , Then go to create the process , Finally start Acitivy, Cold start . There is a problem of white and black screen at startup , It was during this period of time . The system draws the page before loading the layout , First, the window will be initialized (Window), And in this step , The system will be set according to our Theme To specify its Theme  Theme color , We are Style The setting in determines whether the display is white or black .
  • windowIsTranslucent and windowNoTitle, Set both properties to true ( There will be an obvious Caton experience , Not recommended )
  • If the startup page is just a picture , Then set a new theme for the launch page , Set the theme android:windowBackground Property is the background image of the startup page
  • Use layer-list Make a picture launcher_layer.xml, Set it as the background for the specific theme of the launch page , And set it as the background for starting the page layout .
  • Recommended articles :[Android Launch page solution Introduction ](()
8、 Force quote to null, Will it be recycled ?
  • Reference answer :
  • The memory occupied by the object will not be released immediately .
      If a reference to an object is set to null, It just breaks the reference relationship of the object in the current thread stack frame , and   The garbage collector is a thread running in the background , Only when the user thread runs to a safe point (safe point) Or the security zone will scan the object reference relationship , Scanning that the object is not referenced marks the object , At this time, the object memory will not be released immediately , Because some objects are recoverable ( stay  finalize Restore reference in method  ). The object memory will be cleared only when it is determined that the object cannot be recovered .
9、ListView Follow RecyclerView The difference between
  • Reference answer :
  • Animation difference :
  • stay
    RecyclerView
    in , Built in with many animations API, for example :notifyItemChanged(), notifyDataInserted(), notifyItemMoved() wait ; If you need to customize the animation effect , By implementing (RecyclerView.ItemAnimator class ) Complete custom animation effects , And then call RecyclerView.setItemAnimator();
  • however
    ListView
    No animation effect , But we can be in Adapter Realize it by yourself item Animation effect of ;
  • Refresh the difference :
  • ListView Generally, global refresh is used to refresh data in notifyDataSetChanged(), In this way, it will consume a lot of resources ;
    Local refresh cannot be achieved by itself
    , But if it's in ListView Realization
    Partial refresh
    , Still achievable , When one item Data refresh , We can do it in Adapter in , Achieve one onItemChanged() Method , Get this in the method item Of position( Can pass getFirstVisiblePosition()), And then call getView() Method to refresh this item The data of ;
  • RecyclerView Local refresh can be realized in , for example :notifyItemChanged();
  • Cache difference :
  • RecyclerView Than ListView More than two levels of cache , Support multiple remote devices ItemView cache , Support developers to customize cache processing logic , Support all RecyclerView share RecyclerViewPool( Buffer pool ).
  • ListView and RecyclerView The caching mechanism is basically the same , But the cache is used differently
  • Recommended articles :
  • [【 tencent Bugly Dry cargo sharing 】Android ListView  And  RecyclerView  Comparative analysis — Caching mechanisms ](()
  • [ListView  And  RecyclerView  Simple comparison ](()
  • [Android Development :ListView、AdapterView、RecyclerView Comprehensive analysis ](()
10、ListView Of adapter What is it? adapter
  • Reference answer :
  • null
  • BaseAdapter
    : abstract class , In actual development, we will inherit this class and rewrite related methods , The most used adapter !
  • ArrayAdapter
    : Support for generic operations , The simplest adapter , Only one line of text ?
  • SimpleAdapter
    : An adapter with good scalability , You can customize a variety of effects !
    《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 】
     * 
    SimpleCursorAdapter
    : For displaying simple text types listView, It's usually used in databases , But it's a bit out of date , It is not recommended to use !
11、LinearLayout、FrameLayout、RelativeLayout Performance comparison , Why? ?
  • Reference answer :
  • RelativeLayout Will let son View call 2 Time onMeasure,LinearLayout  There is weight when , Will also call the sub  View 2 Time onMeasure
  • RelativeLayout The son of View If the height and RelativeLayout Different , It will lead to efficiency problems , space in between View When it's complicated , This problem will be more serious . If possible , Use as much as possible padding Instead of margin.
  • Without affecting the depth of the hierarchy , Use LinearLayout and FrameLayout instead of RelativeLayout.

JNI

1、 Yes JNI Do you understand
  • Reference answer :
  • Java The advantages of
    Cross platform
    , But also because of its cross platform characteristics, it
    The ability of local interaction is not strong enough
    , Some operating system related features Java Unable to complete , therefore
    Java Provide JNI Designed to interact with native code , adopt JNI, Users can call C、C++ Write native code
  • NDK yes Android A collection of tools provided , adopt NDK Can be in Android It is more convenient to pass through JNI Access local code , The advantage is that
  • Improve the security of the code . because so Library decompilation is difficult , therefore NDK Improved Android The security of the program
  • It is convenient to use the existing C/C++ Open source library
  • It is convenient for platform transplantation . adopt C/C++ The dynamic library can be easily used on other platforms
  • Improve the execution efficiency of the program in some specific situations , But it doesn't improve significantly Android The performance of the program
2、 How to load NDK library  ? How to be in JNI Register in Native function , There are several ways to register  ?
  • Reference answer :

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