Share a wave of your own Android interview questions in 2021

Share a wave of your own Android interview questions in 2021

  1. How does RecyclerView work? Different from ListView, recyclebin mechanism
  2. Principle of Event Distribution
  3. Screen refresh mechanism (keywords vsync Cherorghapher SurfaceFlinger, etc.)
  4. Why not recommend the new Thread () method to create threads, thread pool advantages
  5. How to create a thread in normal times, how to realize it internally in rxjava
    • Thread pool+Handler
  6. How to do drawing optimization, how to realize lazy loading of recyclerview item (such as inserting an advertisement item)
  7. How to directly locate the ANR, the stack information can not be directly located, how to solve it (see systrace)
  8. ASM dynamic technology talk about, AOP, aspect j realization principle
    • ASM: for bytecode instrumentation
    //Introduction to the overall process //1. Use asm to provide classReader to read java source files //2. Implement bytecode instrumentation through the classReader.accept function //2.1 Custom class visitors, such as `MyClassVisitor extends ClassVisitor`, return our custom method visitors in the visitMethod method //2.2 Custom method visitors, such as `MyMethodVisitor extends AdviceAdapter`, write the code to be added in onMethodEnter and onMehodExit //2.2.1 The following function call is equivalent to the java code `System.currentTimeMillis();` //``` //invokeStatic(Type.getType("Ljava/lang/System;"),new Method("currentTimeMillis", "()J"));// //``` // //3. Modify the java source file through the classWriter provided by asm. If the output directory is the same, the original source file will be overwritten to achieve the purpose of bytecode modification Copy code
  9. How to do gradle custom task
  10. What is the use of kotlin scope? Do you know the principle of coroutine?
  11. Why does the Ali development protocol not recommend thread pools
  12. How to write singletons in normal times, and how to ensure thread safety for static internal singletons
  13. Do you know the principles of commonly used open source frameworks?
  14. What is AIDL
  15. How to use in custom view development
  16. Describe the Handler mechanism as a whole, why the for loop in looper does not get stuck
  17. Talk about the overall project structure and difficulties, how to solve these difficulties
  18. How MVP is implemented, why not use MVVM, where is MVVM better than MVP
  19. Talk about JVM? Talk about the class loading process? How to store basic types and object types in methods?
  20. What about the structure and principle of HashMap? Is it an array index calculated directly with hashcode?
  21. The difference between HTTP and https, the port number (80 and 443) (I did not ask about the tsl process and the tcp handshake process, but it is better to prepare)
  22. How does webSocket ensure a stable connection, such as what to do after the lock screen wakes up
    • Service+ broadcast, update ActivityUI through broadcast
    • Heartbeat detection and reconnection, such as checking the connection status every 10s
    • www.jianshu.com/p/7b919910c...
  23. String equals and ==
    • Value comparison and memory address comparison
  24. Have you ever used hook technology (the interviewer said that the plug-in technology life cycle is difficult to manage)
    • weishu.me/2016/01/28/...
    • Activity start
      • When the activity starts, AMS will check whether the activity is registered in the manifest file when the activity starts, if it is not registered, it will throw an exception
      • If AMS does not throw an exception, it can be started without registration, so hook is required
    • Hook technology:
      • What is Hook? Hook means hook in Chinese. Simply put, its role is to change the normal execution flow of the code .
      • Techniques to implement hooks: reflection and dynamic proxy
    • Hook point: The place where the hook hangs is the Hook point.
    • The principle of finding Hook points:
      • 1. Try to static variables or singleton objects. The reason is that static variables are generally not modified
      • 2. Try to Hook publit's objects and methods. The reason is that public generally provides methods for external calls, and Google engineers generally do not modify them.
  25. Show intent and implicit intent
  26. How ThreadLocal is implemented
    • Each thread has a member variable ThreadLocalMap
    • ThreadLocal is stored in ThreadLocalMap
    • Therefore, when each thread accesses ThreadLocal, it accesses it from the internal ThreadLocalMap, and does not need to compete with other threads.
  27. Will IntentService have ANR problems?
    • In theory, the execution of time-consuming tasks in IntentService will not ANR
    • An IntentService creates a thread internally. Through the Handler Message Looper provided by Android, these message processing classes constitute a message processing model. So the onHandleIntent method of IntentService is actually handled in a child thread created in IntentService.
  28. view measurement mode
    • UNSPECIFIED: The parent container does not impose any restrictions on the View, it must be as large as possible. Often used inside the system.
    • EXACTLY (exact mode): The parent view specifies an exact size SpecSize for the child view. Correspond to match_parent or specific value in LyaoutParams.
    • AT_MOST (maximum mode): The size cannot exceed a certain value, such as matchparent, the maximum cannot exceed the parent container. The parent container specifies a maximum size SpecSize for the child view, and the size of the View cannot be larger than this value. Corresponds to wrap_content in LayoutParams.
  29. Can String be inherited? What are the final methods in String? The splicing operation generates a new string, why?
    • Cannot be final
    • To be added
    • The internal is to create a temporary StringBuilder object, call the append method to achieve (verifiable by bytecode)
    • StringBuffer and StringBuilder: The methods of StringBuilder are not thread-safe, but the speed has advantages over StringBuffer
  30. 8 basic types to talk about
    • byte (1 byte)
    • boolean (1 byte)
    • char (character, 2 bytes)
    • short (short integer, 2 bytes)
    • int (integer, 4 bytes)
    • long (long integer, 8 bytes)
    • float (floating point number, single precision, 4 bytes)
    • double (double precision, 8 bytes)
  31. What does java polymorphism mean?
    • Polymorphism is another important feature of object-oriented programming. It means that after the properties and methods defined in the parent class are inherited by the subclass, they can have different data types or exhibit different behaviors, which makes the same property or method It has different meanings in the parent category and its subcategories.
    • For object-oriented, polymorphism is divided into compile-time polymorphism and runtime polymorphism. Among them, polymorphism at compile time is static, which mainly refers to method overloading, which distinguishes different methods according to different parameter lists. After being compiled, it will become two different methods, and there is no talk of polymorphism at runtime. While runtime polymorphism is dynamic, it is achieved through dynamic binding, which is commonly referred to as polymorphism.
    • Java has three necessary conditions for achieving polymorphism: inheritance, rewriting, and up-casting. Only when these three conditions are met, can developers use unified logic to implement code to process different objects in the same inheritance structure, thereby performing different behaviors.
      • Inheritance: In polymorphism, there must be subclasses and parent classes that have inheritance relationships.
      • Rewrite: The subclass redefines some methods in the parent class, and when calling these methods, it will call the method of the subclass.
      • Upcasting: In polymorphism, the reference of the subclass needs to be assigned to the parent class object. Only in this way can the reference be able to call the method of the parent class and the method of the subclass.
  32. java generics
    • Function: Help to check the type in the code and report errors in advance; Automatically forced conversion.
    • Upper Bound:? The wildcard + extends keyword,? Specifies the upper bound of the generic type, and the generic instance of the subclass can be used to declare the parent class
      ArrayList<? extends Fruit> fruits2 = new ArrayList<Apple>(); Copy code
    • Lower bound: In generics, use? + super keyword declaration, you can use the generic instance of the parent class to declare the subclass
      List <? Super Apple> apples2 = new ArrayList <Fruit> (); Copy the code
  33. What about the Glide source code?
  34. How many ways does the child thread send messages to the main thread?
    • Handler
    • activity.runOnUiThread(runnable)
    • view.post
    • view.postDelay
  35. Dalvik and ART
    • Before 4.4 : Dalvik virtual machine executes dex bytecode, which is interpreted and executed. Starting from the Android 2.2 version, JIT just-in-time compilation (JustInTime) is supported to select hot codes (codes that are frequently executed) for compilation or optimization during the running of the program.
    • 5.0-7.0 : ART (Android Runtime) is a developer option introduced in Android 4.4, and is also the default Android runtime for Android 5.0 and higher. The ART virtual machine executes local machine code. The Android runtime is replaced from the Dalvik virtual machine to the ART virtual machine. Developers are not required to directly compile their applications into the target machine code. The APK is still a file containing dex bytecode.
      • During the installation process of the application under Dalvik, an optimization will be performed, and the dex bytecode will be optimized to generate an odex file. The most appropriate AOT time to translate the application's dex bytecode into local machine code under Art also occurs when the application is installed. ART introduces a pre-compilation mechanism (Ahead OfTime). During installation, ART uses the dex2oat tool that comes with the device to compile the application, and the bytecode in the dex will be compiled into local machine code .
    • After 7.0 : ART uses pre-(AOT) compilation, and mixes AOT compilation, interpretation and JIT from Android N.
      • 1. No AOT compilation is performed during the initial installation of the application (installation is fast again), interpretation and execution during operation, JIT for frequently executed methods, and T-compiled methods will be recorded in the Profile configuration file.
      • 2. When the device is idle and charging, the compiling daemon will run and AOT compile common codes according to the Profile file. To be used directly in the next run.
  36. Android class loader
    • Activity is loaded by PathClassLoader
  37. OKHTTP related:
    • Distributor summary:
      • For synchronous requests, the distributor only records the request to determine whether IdleRunnable needs to be executed
      • For asynchronous requests, submit the request to the dispatcher:
      • Q: How to decide whether to put the request into ready or running?
        • A: If the number of current requests is greater than or equal to 64, put it into ready; if it is less than 64, but there are already less than 5 requests from the same domain host, put it into ready!
      • Q: What are the conditions for moving from running to ready?
        • A: After each request is executed, it will be removed from running, and at the same time, the same logical judgment as in the first step is performed to decide whether to move!
      • Q: What is the working behavior of the distributor thread pool?
        • A: No waiting, maximum concurrency
    • Interceptor:
      • 1. The retry interceptor is responsible for judging whether the user has cancelled the request before handing over (to the next interceptor). After the result is obtained, it will judge whether redirection is required according to the response code, and if the conditions are met, it will restart Execute all interceptors.
      • 2. Before handing over, the bridge interceptor is responsible for adding the request header necessary for the HTTP protocol (such as Host) and adding some default behaviors (such as GZIP compression); after obtaining the result, call the save cookie interface and Parse GZIP data.
      • 3. The cache interceptor, as the name implies, reads before handing over and determines whether to use the cache; after obtaining the result, it determines whether to cache.
      • 4. Before handing over, the connection interceptor is responsible for finding or creating a connection and obtaining the corresponding socket stream; no additional processing is performed after the result is obtained.
      • 5. Request the server interceptor to communicate with the server, send data to the server, and parse the read response data.
  38. Examples of CAS atomicity:
    • There is a value count at a location in memory
    • Multiple threads operate count++, suppose a thread changes the value of count from 0 to 1
    • cpu provides an atomic instruction
      compare and swap
      , This atomic instruction receives three parameters, count memory address expected value (old value) new value
    • So the cpu will first compare whether the value of count in the memory is the expected value, and if it is to exchange the new value with the old value
    • Modern cpu combines two operations into one through an atomic instruction, ensuring that the two operations are either completed or not completed.
    • If it is not the expected value, for example, the count value is not 0 but 2, so the cpu will use a spin operation (that is, a loop), 2+1, re-call the CAS instruction, and exchange the old value back to 3, that is Continuous detection through a loop
  39. The realization mechanism of atomic variables in JDK
    • As in the above question, AtomicXxx is to calculate and compare the value of the variable in the memory with the old value through a cycle of non-stop value calculation until it succeeds
  40. Blocking queue
    • When the queue is empty, when you want to fetch data from the queue, it will be blocked
    • When the queue is full, when you want to store data in the queue, it will also block
    • In jdk, there is a blocking queue interface BlockingQueue
      • Non-blocking methods add and remove
        • The add method is used to store elements. When the queue is full, an exception will be thrown
        • The remove method is used to fetch elements. When the queue is empty, an exception will be thrown
      • Non-blocking method offer and poll
        • Offer is used to add elements, if the queue is full, it will return false
        • poll is used to fetch elements, when the queue is empty, it will return null
      • What really embodies the blocking is the take and put methods
        • take is used to take elements, if the queue is empty, the take method will block there
        • put is used to store elements, if the queue is full, the put method will block there
    • Blocking queues are used to solve producer-consumer problems
      • effect:
        • Decoupling of producers and consumers
        • Balance the issue of producer and consumer performance balance
      • Commonly used blocking queue
        • ArrayBlockingQueue: A bounded blocking queue composed of an array structure.
        • LinkedBlockingQueue: A bounded blocking queue composed of a linked list structure
        • PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.
        • DelayQueue: An unbounded blocking queue implemented using priority queues.
        • SynchronousQueue: A blocking queue that does not store elements.
        • LinkedTransferQueue: An unbounded blocking queue composed of a linked list structure.
        • LinkedBlockingDeque: A two-way blocking queue composed of a linked list structure.
  41. The state of the thread, wait and notify
  42. Thread pool classification and application scenarios
  43. The difference between synchronized objects and classes
  44. Will instruction retake occur due to the effect of volatile keyword (no)
  45. Why does zygote start the application with socket instead of binder
  46. Why RelativeLayout draws more times than LinearLayout
  47. Who registers for service with AMS
  48. Surface principle, how pixels are rendered to the screen, how does the Framework layer do
  49. Generic function (compilation check), what other functions
  50. mvc mvp mvvm draw a picture to make it clear their differences
  51. handler barrier message, how to get asynchronous message
  52. Componentized communication principle
  53. Why does linkedHashmap use a doubly linked list
  54. Postlayout details and process
  55. Http2.0 multiplexing talk about
  56. How to update the UI in the child thread
  57. Retrofit-Package of Okhttp:-Package of OkhttpClient-Package of Request-Package of Call-Package of Request Queue
    • Retrofit advantages:
      • Adaptation of network request parameters -> retrofit 23 annotations, protocol form, RestFul
      • Encapsulate okhttp, call
      • Data result package
  58. Cold start optimization:
    • adb command:
      am start -S -W com.dsh.demos/.MainActivity
      Time-consuming to start printing
    • AS comes with cpu profiler to analyze the startup time-consuming function call process
      • cpu profiler can only be used above 8.0
      • DebugTracing is used below 8.0, the xxapp.trace file will be generated in the SDK card
        • Open in the Application construction method
          Debug.startMethodTracing("xxapp");
        • Start Activity closed in onWindowFocusChanged callback
          Debug.stopMethodTracing();
    • AsyncLayoutInflater loads xml layout asynchronously
    • Turn on strict mode StrictMode to check violations in the code, such as IO operations executed in the main thread are not allowed by strict mode
    • Start black and white screen problem:
      • Add a theme with a background image to the start page
      • Change back to the theme in Activity onCreate
    • Start optimization related
      • 1). Reasonably use asynchronous initialization, delayed initialization, and lazy loading mechanisms.
      • 2). Avoid time-consuming operations during startup. For example, database I/O operations should not be executed on the main thread.
      • 3). Class loading optimization: Class loading is performed asynchronously in advance.
      • 4). Reasonably use IdleHandler for delayed initialization.
      • 5). Simplify the layout
  59. Stuttering and layout optimization
    • Both the cpu profiler and DebugTracing consume additional performance, so use the API sampled by DebugTracing to track the startup process and check the time-consuming operations in the code.
      • Debug.startMethodTracingSampling(...)
    • Turn on gpu overdrawing debugging
    • AS Layout Inspector inspects the layout level
    • Systrace analysis program stuck, commonly used to analyze sliding stuck, you can view the thread and cpu execution process and time-consuming statistics
    • Code detection method:
      • Use the log match printed by Looper of the UI thread -> BlockCanary principle
      • Use Choreographer.FrameCallback callback detection
  60. ANR analysis
    • Through the logcat log, the traces file confirms the traces file and CPU usage at the time point of anr occurrence
    • /data/anr/traces.txt
    • Main thread state
    • Other thread status
    • ANR online monitoring :
      • FileObserver: monitor a directory/file status change, create, delete files, if anr file is generated, upload it to the server
        • Implementation: Inherit the FileObserver, handle uploading and other logic in the onEvent callback
      • WatchDog: Monitoring system deadlock and other situations, developers can use similar ideas to monitor ANR
  61. Charles https packet capture principle
  62. apk signature keystore principle v1 v2 v3 principle
  63. HTTPS TLS handshake process
  64. What is webSocket and why not keep-alive of http
    • keep-alive
      • If you send requests serially, you can always reuse a connection, but the speed is very slow. Each request has to wait for the completion of the previous request before sending it.
      • If the requests are sent in parallel, then each request can only be a three-way tcp handshake to establish a new connection.
  65. How to solve the component dependency, such as A depends on B, but we don t need B, how to remove the dependency on B
  66. How to solve the sliding conflict, the principle of NestedScrollView
  67. Viewpager principle
    • Cache: ArrayList cache, at least one cache
    • Lazy loading setOffscreenPageLimit, viewpager+fragment
      • Fragment life cycle is in order:
      onAttach -> onCreate -> onCreatedView - > onActivityCreated -> onStart -> onResume -> onPause -> onStop -> onDestroyView -> onDestroy -> onDetach copy the code
      • The realization of ViewPager + Fragment we need to pay attention to several life cycles:
      onCreatedView + onActivityCreated + onResume + onPause + onDestroyView duplicated code
      • Non-life cycle functions:
      setUserVisibleHint + onHiddenChanged duplicated code
  68. Dagger2
    • Is an IOC dependency injection framework, mainly using apt compile-time annotation technology
    • Singleton problem: Assuming that a singleton SingleTon is injected into ActivityA and ActivityB at the same time, and A jumps to B, then the singleton in A and the singleTon in B will not be the same object, which is caused by the inconsistency of the provider
      • The solution is to inject in Application, and provide a singleton get method getAppComonent (), and then inject in A and B
        ((MyApplication)getApplication().getAppComponent().injectAActivity(this);)
        Can