I went round and round from Android to Java and back to Android. I met with many big companies, such as Alibaba, JINGdong, Xiaomi, Toutiao, Zhihu, Tencent and Youzan, and also got several offers. Thank you for your attention, let me in Jane book above also mixed a Jane book programmer excellent author title, so in order to reward you, a most complete Android book was born. This is my collection of niuke.com, Baidu, Jane and other sites dozens of interviews and my own experience of the collection, I hope you like. (PS: Of course there will be flaws, if there is any problem, welcome to leave a message or add me to QQ to discuss 3-5 years of Advanced Java architects can contact QQ number: 2750253501, exchange QQ group: 668041364)

1. Android event distribution mechanism, please explain the whole process in detail

Event distribution (interview).png

2. Android View drawing mechanism and loading process, please explain the whole process in detail

1. The ViewRootImpl will call performTraversals() and inside it will call performMeasure(), performLayout, performDraw(). 2. PerformMeasure () calls the outermost ViewGroup’s onMeasure() –>onMeasure(), which is abstract but provides measureChildren(). MeasureChild () = measureChild() = measureChild() = measureChild() = measureChild() = measureChild() = measureChild() Then call the child View’s measure() to the View’s onMeasure()–>setMeasureDimension(getDefaultSize(),getDefaultSize())). GetDefaultSize () returns measur by default ESpec measurement values, so inherit View to customize wrAP_content needs to be rewritten. 3. PerformLayout () calls the outermost ViewGroup layout(L,t,r,b), where the View uses setFrame() to set the position of the View’s four vertices. In onLayout(abstract method) determine the position of the child View, such as LinearLayout will traverse the child View, loop setChildFrame()–> child View.Layout (). 4. PerformDraw () will call draw() of the outermost ViewGroup: background-draw (), onDraw(), dispatchDraw(), onDrawScroll Bars()(draw decoration). 5.MeasureSpec is an Int composed of two specmodes (UNSPECIFIED, EXACTLY, Match_parent, AT_MOST, warP_content) and 30 specSizes EasureSpec is determined by the size of the window and its LayoutParams. Other views are determined by the parent’s MeasureSpec and the parent’s LayoutParams. The ViewGroup has getChildMeasureSpec() to get the child’s MeasureSpec. Get the width and height after measure() in three ways: 1. Call in Activity#onWindowFocusChange(); 2. Viet.post (Runnable) posts the code to the end of the message queue. ViewTreeObservable. 3. Loading process of four android components, please introduce it in detail

1. The loading process of the four components of Android: This is a blog I summarized 4

If onNewIntent is used at the top of the stack, start from onResume(). 3. SingleTask: 4. SingleInstance: This type of Activity will be removed from the stack whenever it is used in the stack. A->B->C->D->A->B->C->D ->A->B->C->D

2. The final answer is: There are two stacks, the foreground stack is only D, the background stack from bottom to top is A, B, C

1. The Activity is killed due to a configuration change and the landscape screen changes to portrait: OnSaveInstanceState () is called before onStop to save the data and after rebuilding the Activity, OnRestoreInstanceState () is called after onStart(), and it passes the saved Bundle to onCreate() and it defaults to rebuilding the current view of the Activity, and we can restore our own data in onCreate(). 2. When there is not enough memory to kill the Activity, the priorities are foreground visible, visible not foreground, and background. 7. What is the difference between the two startup methods in the Service lifecycle

1.context.startService() ->onCreate()- >onStart()->Service running- >(if context.stopService() is called)->onDestroy() ->Service shut down 1. If the Service is not already running, call onCreate() and then onStart(); 2. Only onStart() is called if the Service is already running, so the onStart method of a Service may be called multiple times. 3. Call stopService directly onDestroy, 4. If the caller simply exits without calling stopService, the Service will always run in the background. The caller of the Service can stop the Service by stopService after starting it again. 2.context.bindService()->onCreate()->onBind()->Service running–>onUnbind() -> onDestroy() ->Service stop 1. OnBind will return the client an instance of the IBind interface, which allows the client to call back on methods of the Service, such as getting the status of the Service running or other operations. If the Context exits, the Service will call onUnbind->onDestroy to exit. 3. So the life cycle of calling bindService is onCreate –> onBind –> onUnbind –> onDestory. 8. How can service not be killed

Upgrade service priority 2. Upgrade service process priority 3. Restart Service 9 in onDestroy. What is the difference between static Broadcast and dynamic Broadcast

1. Dynamic is safer than static 2. Static is initialized when the app starts. Static yes Dynamic No 4. Lifetime. The lifetime of static broadcast can be much longer than that of dynamic broadcast 5. Priority Dynamic broadcast has a higher priority than static broadcast. 10. What data types can be transmitted by an Intent

1.Serializable 2. Charsequence: mainly used to pass String, char, etc. 3. Parcelable 4

JSON is much faster than XML. 2.JSON data is smaller than XML. 3. The basic principle of parsing is: lexical analysis 12. The compilation process of a language

1. Lexical analysis: divide a string of text into the smallest structure according to rules, including keywords, identifiers, operators, delimiters and constants, etc. The general implementation methods are automata and regular expressions. 2. Grammar analysis: combine a series of words into a grammar tree. General implementation methods are top-down and bottom-up 3. Semantic analysis: context-related properties of structurally correct source programs are examined 4. 5. Code optimization: optimize the generated object code, 13. What are the categories of animation, and what are their characteristics

1. Basic principle of animation: In fact, it uses interpolator and estimator to calculate the properties of View at each moment, and then realizes the animation effect of View by changing the properties of View. 2.View animation: Only the image changes, the actual position of the View is still in the original place. 3. Frame animation is an animation that is played using an AnimationDrawable after a series of images have been defined in XML. 1. Interpolator: the function is to calculate the percentage of the property change according to the percentage of time passing 2. Estimator: a class that calculates how much a property has changed on the basis of 1.Handler, Looper message queue model

1.MessageQueue: Read will automatically delete messages, single linked list maintenance, has advantages in insert and delete. In its next() it loops endlessly, checking for messages, returning them and removing them. 2. The stars: When Looper is created, a MessageQueue is created. When loop() is called, the message loop starts. Loop () is also an infinite loop, and MessageQueue’s next() is called repeatedly. Otherwise it blocks in messageQueue’s next(). MessageQueue’s quit() is called when Looper’s quit() is called, next() returns null, and the loop() method exits. Handler: Construct a Handler in the main thread and call sendMessage() in another thread. A message will be inserted into the MessageQueue of the main thread and used by Looper. 4. The main thread of the system starts the main thread for entry in the Main () of ActivityThread, which defines the inner class Activity.h that defines a series of message types, including the start and stop of four components. 5.MessageQueue and Looper are one-to-one, while Handler and Looper are many-to-one 15. How to exit and terminate the App

1. Set up a stack of activities by yourself and finish() each one

1. Binder is used when activities communicate with services. If you own a process, you can inherit the Binder and use Service in your Activity. When not in the same process, use AIDL to get the system to create a Binder and then operate on the remote Service in the Activity. 2. Binder generated by the system for us: The Stub class contains the ID of the interface method, the identifier of the Binder, and the asInterface(IBinder). The onTransact() method is used to make remote calls to the Activity between different processes. Service 2. The Proxy class is a Proxy. There’s IBinder mRemote(the Binder on the remote side), both interfaces implemented by agents that ultimately do the actual work in onTransact() on the remote side. 3. Any end of the Binder is a copy, that end can be operated by the other end, because the Binder body can operate the local end when defined. Therefore, a Binder on the local end of the Activity can be passed to the Service end to operate on the Listener. A RemoteCallbackList container can be used to install the Listener to prevent problems caused by serialization. 4. When the Activity end calls the remote end, the current thread suspends and wakes up when the method is finished processing. 5. A single Service is too expensive for an AIDL, so Binder pools can be used to create an AIDL that returns IBinder and then returns the specific AIDL based on the parameters passed into the method. 6. Methods of IPC include: Bundle (passed in when the Intent is launched, but only once), file sharing (a special case for SharedPreference, which is cached in memory), using Messenger(which uses AIDL at the bottom, so you define Messenger where you want to operate), AIDL, ContentProvider(inherits a ContentProvider in this process, calls SQLite in this process, query in other processes), Socket 17. Describes a cross-process communication

Client, Proxy, serviceManager, BinderDriver, IMPL, and Service 2. The client sends a Binder request for service information to BinderDriver. The serviceManager finds its own request in BinderDiriver and returns clinet’s requested service data to the client, completing a Binder communication Clinet calls the proxy method and the proxy sends the request to BinderDriver. Then the Binder thread pool of the Service circulates and finds its own request. The impL then processes the request and returns, completing the second Binder communication 4. The intermediate client can suspend, but also can not suspend, there is a keyword oneway can solve this 18. Android important terms

ActivityManagerServices, hereinafter referred to as AMS, server-side objects, (2) is responsible for all the Activity in the system life cycle ActivityThread, the real entrance of App. When the App is started, main() is called to start running, opening the message loop queue, which is known as the UI thread or main thread. Work with ActivityManagerServices to manage activities. 3.ApplicationThread is used to implement interaction between ActivityManagerService and ActivityThread. When ActivityManagerService needs to manage the Activity lifecycle of the related Application, it communicates with the ActivityThread through an ApplicationThread proxy object. 4.ApplicationThreadProxy is the proxy for ApplicationThread on the server and communicates with the ApplicationThread on the client. It is through this agent that AMS communicates with ActivityThread. 5.Instrumentation, each application has only one Instrumentation object, and each Activity has a reference to the object. Instrumentation can be understood as the steward of the application process. When an ActivityThread wants to create or pause an Activity, it needs to perform specific operations through Instrumentation. 6.ActivityStack is used for AMS stack management, which is used to record the sequence of activities that have been started, status information, etc. Use ActivityStack to determine if a new process needs to be started. 7.ActivityRecord, the managed object of ActivityStack. Each Activity has an ActivityRecord in AMS, which records the status of the Activity and other management information. This is the image of the Activity object on the server side. 8.TaskRecord: AMS abstracts the concept of a “Task”, which is a stack of recording ActivityRecords. A “Task” contains several ActivityRecords. AMS uses TaskRecord to ensure the order in which an Activity starts and exits. This concept should be familiar if you are familiar with the four launchmodes for your Activity. 19. Understand Windows and WindowManager

1. Windows are used to display views and receive various events. There are three types of Windows: Apply Window(each Activity corresponds to a Window), child Window(cannot exist independently and is attached to a specific Window), and system Window(Toast and status bar). Application Window in 1-99, child Window in 1000-1999, system Window in 2000-2999. Windows Manager provides three functions: add, delete and modify View. 3.Window is an abstract concept: Each Window corresponds to a View and ViewRootImpl. The Window is connected to the View through ViewRootImpl. The View is the entity of the Window and can only be accessed through WindowManager. 4. The implementation of WindowManager is WindowManagerImpl which delegates to WindowManagerGlobal to operate on Windows. Four of them a List to store the corresponding View, ViewRootImpl, WindowManger. LayoutParams and are deleted View 5. The Window of the entity is exist in the distant WindowMangerService, So adding, deleting, and modifying Windows on the local side is modifying the List above and then redrawing the View via ViewRootImpl and modifying Windows on the remote side via WindowSession(one per application). 6.Activity create Window: The Activity creates the Window in Attach () and sets its callbacks (onAttachedToWindow(), dispatchTouchEvent()). The Window of the Activity is implemented by creating PhoneWindow with the Policy class. Then call the PhoneWindow setContentView with Activity#setContentView(). 20. The Bitmap handle

Bitmapfactory. Option is used to compress the image. InSampleSize indicates a reduction of 2^(insamplesize-1). 2.BitMap cache: 1. LruCache is used for memory cache. 2. Use DiskLruCache to cache disks. 3. Implement an ImageLoader process: synchronous asynchronous loading, image compression, memory cache, network pull 1. Synchronous loading creates only one thread and loads images in sequence. 2. Asynchronous loading uses a thread pool, so that all existing load tasks are in different threads. To avoid too many asynchronous tasks, only enable picture loading when the list is still. How to implement a Network framework (see Volley)

1. Cache queue. The cache content with URL as key can be processed by referring to Bitmap. 2. Network request queue, using thread pool for request. 3. Provide parsing of various types of return values such as String, Json, images, etc. 22. Basic knowledge of ClassLoader

1. Parent delegate: a ClassLoader class is responsible for loading all classes involved in this class. When loading, it will determine whether the class has been loaded, and then recurse to its parent ClassLoader to find. 3.ClassLoader isolation problem The JVM recognizes a class by: ClassLoader ID +PackageName+ClassName. 1. Let the parent ClassLoader load the public Jar and the child ClassLoader load the Jar containing the public Jar. In this case, the child ClassLoader will first look for the parent ClassLoader when loading the public Jar. (Java only) 2. Overwrite the ClassLoader that loads jars containing public jars. Find the ClassLoader that has loaded the public jars in the loadClass. (Java only) 3. Remove the public Jar when generating the Jar containing the public Jar. DynamicLoadApk is used as an example

1. Use DexClassLoader to load and access the DEX package in APK. 2. Loading resources is a big problem because there are no resources in apK in the host program, so calling R resources will get an error. Therefore, we use getAssets() and getResources() in the Activity that implement ContextImpl, plus reflection. 3. Since the system has many initialization actions to start the Activity, and manual reflection is difficult to complete, so we can use the interface mechanism, extract most of the Activity life cycle into the interface, and then call the plug-in Activity life cycle through the proxy Activity. Also, if you add a new lifecycle method, you just need to declare it in the interface and in the proxy. 4. Cons: 1. Use this with caution, because using this in APK does not represent the activity in the host, although it is fine if this simply represents its own interface. In addition, you can use that instead of this. 2. Service and Broadcast 3 with static registration are not supported. Implicit invocation of activities in LaunchMode and Apk is not supported. 24. Hot fix: Andfix is an example

1. General principle: APKPatch compares the two APKs once and finds out the different parts. You can see the generated Apatch file, change the suffix to zip and unzip, there is a dex file. Look at the source code through Jadx, which is the class file where the repaired code is located. The changed classes are added with a _CF suffix, and the changed methods are annotated with an @methodreplace annotation, which specifies the method to be replaced by clazz and method. Then the client SDK gets the patch file and looks for the replacement method based on the annotations. Finally, the JNI layer completes the method replacement. 2. New classes and fields cannot be added, patch files are easily decompiled, and hardening platforms may disable hot patch functionality 25. Thread synchronization problem, commonly used thread synchronization

Sycn: ensures atomicity, visibility and orderliness 2. Lock: ensures atomicity, visibility and orderliness 1. Spin lock: allows a thread to execute an empty loop without being suspended if it has not acquired the lock. 1. Advantages: Threads are less likely to be suspended and thread execution is more consistent. Used for concurrent threads where lock contention is not intense and lock occupancy is short. 2. Disadvantages: excessive waste of CPU time, a thread trying to acquire a spin lock twice in a row causes deadlock 2. Blocking Lock: a thread without a Lock waits or suspends, Sycn, Lock 3. Reentrant Lock: a thread can acquire the Lock more than once, Sycn, Lock 4. Pessimistic Lock: every time it tries to retrieve data, it thinks someone else will modify it, so it blocks all other threads Sycn, Lock 5. Optimistic lock: Every time I go to get the data, I think that others will not modify it, so I will not lock it, but I will judge whether others have updated the data during this period, and I can use the version number and other mechanisms. 6. Display Lock and built-in Lock: Display Lock is defined by Lock, and built-in Lock is synchronized. 7. Read-write locking: To improve performance, Java provides read 3.volatile 1. Only visibility can be guaranteed, but atomicity cannot be guaranteed. 2. There are three steps in the increment operation. Actions: memory value V, old expected value A, value B to be modified, change memory value to B and return true if and only if expected value A and memory value V are the same, otherwise do nothing and return false. 2. The local copy is A, the shared memory is V, and thread A needs to change V to B. At some point, thread A needs to change V to B. If A and V are different, it means that another thread is modifying V, and the modification fails. Otherwise, it means that no other thread is modifying V, so change V to B. 3. Limitation: If V is changed to V1 and then changed to V, CAS cannot recognize the change and still thinks that no other thread is modifying V, then problem 4 will occur. Limitations resolved: bring V to version. 5. Thread insecurity exactly what is the matter: 1. One thread write, multiple threads read, will cause to write half to read 2. 26.Asynctask is related to thread pool, GC (how to determine which memory is GC, GC algorithm)

1.Asynctask: Asynctask class, single-thread thread pool +Handler 2. Thread pools: 1.ThreadPoolExecutor: You can construct a single thread pool, a fixed number of thread pools, or an unfixed number of thread pools by running Executors. 2. ScheduledThreadPoolExecutor: repeat scheduling threads can delay the calling thread or delay. 3.GC related: Important 1. Search algorithm: 1. Reference counting 2. Graph search, accessibility analysis 2. Recycling algorithm: 1. Mark clearing copy: used for young generation 2. Mark finishing: used for old generation 3. Heap partition: 1. Eden 80%, Survivor1 10%, Survivor2 10% 2. Old area 4. Partition of vm stack: 1. Local variable table 2. Dynamic link 4. Method return address 5.GC Roots: 1. Object 2 in vm stack (local variable table in stack frame) reference. Object referenced by class static properties in the method area 3. Object referenced by constants in the method area 4. The object referenced by JNI in the local method stack 27. Network

1.ARP: In IP Ethernet, when an upper-layer protocol sends packets, ARP provides the MAC address of the node with the IP address. HTTPS uses TLS(SSL) for encryption.HTTPS works on TCP port 443 by default. The working process is as follows: 1. Complete the TCP three-way handshake 2. The client authenticates the digital certificate of the server. If yes, go to Step 3. 3. The web page is transmitted in encrypted way, and encrypted with negotiated symmetric encryption algorithm and key to ensure the confidentiality of data. Use the hash algorithm to protect data integrity from tampering. 3. Structure of HTTP request packets, classification of HTTP return codes, differences between 400 and 500 1. Packet structure: 1. Request: request line, header, and data 2. Return: status line, header, and data 2. HTTP return code classification: 1 to 5 Yes: Message, Success, Redirect, client error, and server error 4. 1. Three handshakes: Syn -c = x: indicates that the message is x. Ack -s = x + 1: indicates that the syn-c message is received successfully. Syn-s = y: indicates that the message is the sequence number of Y. Ack -c = y + 1: Indicates that the SYN-s message is received successfully. 2. 4 waves: TCP is in full-duplex mode. 1. Fin-c = x, which indicates that c to S needs to be disabled. Ack -c = y: indicates that the last message of S has been received. 2. Ack -s = x + 1: indicates that the fin-C message to be closed has been received and agreed to be closed. Ack -c = y + 1 ack-c = y + 1 ack-c = y + 1 Slide window, stop waiting, back N, select retransmission 4. Congestion control, slow start, congestion avoidance, accelerated decline, fast retransmission and quick recovery 28. Database performance optimization: indexes and transactions. Read a book about them

29.13.APK packaging process and its contents

Procedure 1. Aapt generates R files. 2. Aidl generates Java files. Compile all Java files into class files. 4. Merge all class files and third-party packages into dex file 5. Consolidate resources, SO files, and dex files into APK 6. Apk signature 7. Apk byte alignment 2. 30. Types and principles of network hijacking: You can search for specific concepts

HTTP hijacking: redirect, JS injection, HTTP injection, packet extension 31. Java class loading process:

1. Load time: before instance creation, static variable or method access, reflection, subclass loading 2. Verification: verify the correctness of file format, metadata, bytecode and symbol reference. 3. Loading: obtain file byte stream according to the full class name, put byte flow into the method area as a static storage structure, and generate class object 4. Preparation: partition memory on the heap for static variables 5. Parsing: Convert symbolic references in the constant pool to direct references 6. Initialize: Initialize static variables 7. Book recommendations: In-depth understanding of Java Virtual machines, blog recommendations: Java/Android Ali interview JVM part understanding 32. Retrofit understanding

Dynamic proxy creates a proxy class for an interface. Reflection parses annotations for each interface and constructs HTTP requests with input parameters. Get the returned HTTP request and use Adapter to parse it into the desired return value. 33. How to store the bundle’s data structure

2. The data passed can be Boolean, byte, int, long, float, double, string, or their corresponding arrays, as well as objects or arrays of objects. 3. The Serializable or Parcelable interface must be implemented when the Bundle passes objects or arrays of objects.

1. Generate a Down event, activity–>phoneWindow–>ViewGroup–>ListView–> Botton, if there is any interception method overwritten, the event may be consumed by the view interception. 2. Without interception, the event arrived at the button. In the process, a view list for event delivery was established. Go to Button’s Dispatch method — onTouch– View available — Touch agent 2. Move button: 1. Generate move event, the listView will block move event 2. The listView will consume the slider 3. Subsequent slides will be consumed by the listView 3. The parent view of the listView will fetch events directly from the listView list and let it consume events. 35. What a service means: A program that executes in the background without an interface

36. Android IPC communication mode, thread (interprocess) communication mechanism

1. Ipc communication mode: Binder, ContentProvider, Socket 2. Operating system process communication mode: shared memory, socket, pipe 37. The difference between operating system process and thread

In short, a program has at least one process, and a process has at least one thread. The scale of thread partition is smaller than that of process, which makes the concurrency of multithreaded program high. 3. In addition, the process has an independent memory unit during execution, while multiple threads share the memory, thus greatly improving the running efficiency of the program. 4. The meaning of multithreading is that in an application, multiple execution parts can be executed simultaneously. In the implementation of HashMap, Capacity is the number of buckets, and Load factor is the maximum proportion of buckets to which buckets are filled. Do not set capacity too high or load factor too low if iteration performance is required.

1. Simply put, a HashMap is an array linked list that automatically expands. 2. Hash key hashCode(), then evaluate index; 2. If there is no collision, put it directly into the bucket; If they collide, they should put them behind buckets in a linked list. 4. If the collision causes the list to be too long (greater than or equal to TREEIFY_THRESHOLD), convert the list to a red-black tree; 5. If the node already exists, replace the old value(ensure the uniqueness of the key) 6. If the bucket is full (exceeding load factor*current capacity), resize is required. 3. Resize: When put, resize occurs if it is found that the bucket is currently occupied by more than the proportion that the Load Factor expects. In the resize process, the bucket is doubled, the index is recalculated, and the node is placed in the new bucket. Select * from MVVM; select * from MVVM; select * from MVVM;

1. MVC: data, View and Activity. The View feeds back operations to the Activity and Activitiy to get data, and the data is refreshed to the View in observer mode. MVP: Data, View, and Presenter. The View gives the operation to the Presenter, and the Presenter gets the data. When the data is retrieved, the Presenter returns the data to the Presenter. Presenter refreshes the View. MVVM: Data, View, ViewModel, ViewModel to retrieve data, data and interface binding, data update interface update. 1. ViewModel business logic can be tested separately. 2. Data and interface binding, do not write garbage code, but reuse uncomfortable 40. Java thread how to implement

1.Thread inheritance 2.Runnale 3. 41.ArrayList how to delete duplicate elements or specified elements;

Delete duplicate: Set 2. Delete specified: iterator 42. How to design in UDP to ensure the reliability of UDP transmission;

1. Simply put, using UDP to build reliable connection-oriented data transmission, to achieve similar to TCP timeout retransmission, orderly accept, reply to confirm, the sliding window flow control mechanism, such as is said to be at the transport layer of a layer (or directly in the application layer) TCP protocol can achieve reliable data transmission mechanism. 2. For example, use UDP packets + serial numbers, UDP packets + time stamps and other methods to implement a reply confirmation mechanism on the server to ensure reliable data transmission over unreliable UDP protocols. Udp-based reliable transport protocols include: RUDP, RTP, UDT 43. Why can internal classes access external classes in Java

1. Because the inner class needs an object from the outer class when it is created, a reference to the outer class is passed in when the inner class object is created. Design the function of contact storage and query on mobile terminal, which data structure can be used to quickly search for contacts? Database index, balanced binary tree (B tree, red black tree)

45. Red-black tree characteristics

1. The root node and leaf node are black. 2. The same number of black nodes per path from root to leaf

1. Synchronization: For the client, the client waits but does not suspend: the main thread calls 2. Asynchronous: For the client, the client initiates a request and calls back the service when it is ready. Blocking: For a Service, the service side is suspended while preparing the IO until it is ready and then wakes up service: bio 3. Non-blocking: For a Service, the service is not suspended during I/O preparation. Instead, the service polls to determine whether the I/O preparation is complete. After the preparation is complete, the following operations are performed: NIO, Linux SELECT, poll, and epoll 4. Multiplex IO: An optimization of non-blocking IO, Java NIO, that uses a single thread to poll for availability of multiple IO ports, notifying the corresponding IO request if one is available, which can greatly improve performance with a single thread poll. 1. I can use multi-thread + blocking I/O to achieve a similar effect, but because in multi-thread + blocking I/O, each socket corresponds to one thread, this will cause a large resource occupation. 2. In multiplexing IO, polling each socket state is done by the kernel, which is much more efficient than user threads. 5. Asynchronous I/O: AIO, the user thread is completely unaware of the I/O, all operations are handed over to the kernel, after I/O completion, the kernel notifies the user thread. 1. This type of I/O is asynchronous. 2, 3, and 4 are synchronous I/OS, because the user thread blocks while the kernel copies data. Java 7 provides Asynchronous IO 47.ConcurrentHashMap internal implementation, HashTable implementation deprecated

1. The reason why HashTable containers are inefficient in a highly competitive concurrent environment is that all threads accessing HashTable must compete for the same lock. If there are multiple locks in the container, and each lock is used to lock one part of the data in the container, then when multiple threads access different data segments in the container, This is the lock fragmentation technique used by ConcurrentHashMap. Data is first stored in segments, and then each segment is assigned a lock. When a thread uses the lock to access one segment of data, Data in other segments can also be accessed by other threads. 2.ConcurrentHashMap consists of Segment array structure and HashEntry array structure. Segment is a ReentrantLock that acts as a lock in ConcurrentHashMap, while HashEntry is used to store key-value pairs. A ConcurrentHashMap contains an array of segments. The structure of a Segment is similar to that of a HashMap. A Segment contains an array of Hashentries. Each Segment contains an element in the HashEntry array. When modifying the HashEntry array, the Segment lock must be obtained. 48. The HandlerThread is what

1.MessageQueue + Looper + Handler 49

OnHandlerIntent () can be called multiple times by startService() for a Service that contains HandlerThread. 50. The class and dex

1. DVM executes dex files, JVM executes class files, and Android programs produce class files after compilation. The dex tool will then process the class files into dex files, and then package the resource files and.dex files into APK files. 2. DVM is register-based virtual machine, while JVM execution is virtual stack-based virtual machine. Register access is much faster than stack access, and DVM can achieve maximum optimization based on hardware, making it suitable for mobile devices. 3. The class file contains a lot of redundant information. The dex tool removes redundant information and integrates all the class files into the DEX file. Reduced I/O operations, improved class lookup speed 51. Memory leaks

1. Another thread holds a Listener, which operates the activity. So when the activity closes at the end of the thread, it’s supposed to be recycled but can’t be recycled. 2. For example, a memory leak caused by a Handler is a Listener. Stop the thread when the activity is closed, or unregister the Listener. Use weak references, so that even if the Listener holds the activity, it will still be reclaimed during GC 4. Tools :LeakCanary 52. Overdraw, Caton optimization:

1. The excessive drawn: 1. Remove the Windows default Background: getWidow. SetBackgroundDrawable (null); 2. Remove unnecessary Background from XML layout files 3. Reduce layout nesting (a manifestation of flat, reduce the depth of View number, also reduce the View tree traversal, rendering time, before and after the work, always according to the View tree node) 4. In introducing the layout file, the outermost layer can replace LinearLayout with merge, RelativeLayout, when this UI elements directly join in the include position 5. Tools: HierarchyViewer View View hierarchy 2. Caton Optimization: 16ms data update 53. Apk Slimming:

1. Classes. dex: Optimize this file by obfuscating the code and removing unnecessary jars and code 2. Resource files: Use the Lint tool to scan for static resources 3 that are not used in your code. Image resources: Tinypng and webP are used. The optimization scheme of image resources is introduced in detail below. The unnecessary vector picture 4.so file will be removed

2. Broadcast timeout is 10 seconds. The timeout for no response to keys is 5 seconds. Background service is 200 seconds 55.Serializable and Parcelable difference

1.P consumes small memory 2. Network transmission with S program using P 3.S data persistence convenience 4

XML key-value pairs stored on the hard disk will cause performance problems.ContextImpl records important data about SharedPreferences, file path, and instance key-value pairs. The read operation blocks until the XML file is fully loaded into memory. After the XML file is fully loaded into memory, the data is directly read from memory. 4. In the case of multiple concurrent COMMIT, the commit data being processed must be updated to disk files before the execution continues, which reduces the efficiency. However, apply is only atomic update to memory, and the subsequent call to apply directly overwrites the previous memory data, thus improving efficiency to a certain extent. 3. Edit () creates a new EditorImpl object each time. SharedPreferences 57 How the operating system manages memory:

1. Use registers to map the process address to physical memory. 2. Virtual memory is used for memory paging management. 4. Page table paging is implemented, that is, page + address offset. 5. If the program’s memory is on hard disk, then page replacement algorithms are used to bring it into memory: first in, first out, least recently used, etc. 6. 58. What happens when a browser enters an address to return results

TCP connection 3. Sending an HTTP request 4. The server processes the request and returns HTTP packet 5. Browser parsing rendered page 6. End of connection 59. When does Java generic type erasure occur and what to note about wildcards.

PECS, extends is good at providing the exact fact that object A is A subset of B, and Super is good at inserting the exact fact that object A is A superset of B 3. Effective Java Notes (excluding deserialization, concurrency, annotations, and enumerations), Android Ali Interview Java Basics 60. Activity lifecycle

1. Life cycle flow of A starting B, back key and then a: A.c reate – > a.s tart – > a.r esume – > Amy polumbo ause — > the biggest reate – > b.s tart – > b.r esume — — > b interface map > a.s top – > p. ause — > b.s top – > b.d estroy – ->a.restart–>a.start–>a.resume 2. SaveInstance is called when destroyed accidentally, and restoreInstance is called when restored. The activity > Window >viewGroup > View recursively calls save to keep the view data, and restore recursively restores the view data. We can do some of our own data operations in it. 61. Algorithms often tested in interviews

2. Various operations of linked list: judge ring formation, judge intersection, merge linked list, count down K nodes, search for link point 3. Binary tree, red-black tree, B-tree definition and time complexity calculation method 4. Dynamic programming, greedy algorithm, simple graph theory 5. 62. The process of starting another process: start an app

63. Open source framework source

1. MVC Framework: 1.Controller controls the Drawable of data displayed in Hierarchy. 2.ImagePipeline is responsible for data acquisition in Controller. The data returned is CloseableImage. 3.Drawee hands over all operations except initialization to the Holder, who holds Controller and Hierarchy. To draw a Drawable, call invalidateSelf() to trigger onDraw(). Container classes (save some Drawable), self-drawing classes (progress bar), graphics transform classes (Scale, Rotate, matrix transform), animation classes (internal refresh, The CloseableImage returned by ImagePipeline is resolved into a Drawable by a single DrawableFactory. 4. The webp and GIF animations are parsed by JNI code. Then other still images are parsed using BitmapFactory for different Android platforms 3. Responsibility chain mode: Producer does not mark n, indicating that only a consumer is provided. “Decoding Producer (N)–” “rotating or cutting Producer (N)–” “encoding picture memory caching” “reading hard disks Caching — Writing hard disk caching — Network producer providing CloseableImage — decoding picture caching consumer –client picture processing consumer — decoding consumer — rotating or cutting con Consumer “consumer” consumer “consumer” consumer “consumer” 1. A CountingLruMap holds cached items that are no longer referenced, and a CountingLruMap holds all items including items that are not referenced. Each time the cache policy changes and the cache configuration is updated, the Map of entries to be destroyed is removed one by one until the cache size matches the configured size. CountingLruMap uses LinkedHashMap to store data. 1.DefaultDiskStorage uses the Lru policy. To prevent all files from being concentrated in one file, create multiple folders with different names and use hash algorithm to disperse cache files. 3. In addition, it maintains a <key,value> key-value pair in memory, because the file changes frequently, so it is only periodically refreshed, so if it cannot find in memory, it has to go to the hard disk to find again. When the disk cache is deleted, the cache key is deleted only when the disk data size exceeds the upper limit. Therefore, no key exists in the memory but does not exist on the disk. Return an Inserter, pass a CallBack in inserter.writeData () that encapsulates the client’s logic for inserting data and file references, and let the internal implementation call the logic for the CallBack to insert file data. The temp suffix is changed to make the file visible to the client only after the commit() call. 1. Use an array to store a bucket containing a Queue. The subscript of the array is the byte size of the memory for which data is applied, and the Queue inside the bucket contains memory blocks. So arrays use sparse arrays 2. There are two ways to allocate memory: 1. Memory allocated on the Java heap 2. Builder, Responsibility Chain, Observer, Agent, Composition, Share, Adapter, Decorator, Policy, Producer, Consumer, Provider 8. Custom count reference: Use a static IdentityHashMap (store the number of times an object is referenced) to be counted, provide a destructor to destroy the resource, and provide a static factory method to copy yourself. When the reference count returns to zero, the destructor will destroy the resource, such as bitmap recycle memory or jNI memory, by calling the JNI method to return the memory. Android Fresco source document translation, from scratch a Fresco hard disk cache, from scratch a Fresco GIF and Webp animation, from scratch a Fresco inside the cache, from scratch a Fresco. 1. Asynchrony uses the Dispatcher to dispatch requests stored in the Deque to individual threads in the thread pool. 2. When the task is finished, finally will be executed with or without exceptions. The Finished function of the Dispatcher will be called, which will remove the running task Call from the runningAsyncCalls queue and move the cache queue forward. 2. Connection pool: 1. A Connection encapsulates a socket, and a ConnectionPool stores all connections. StreamAllocation is a unit of reference count. 2. When a request obtains a Connection, a StreamAllocation is passed in. Each time a Connection is referenced by an upper-layer application, StreamAllocation adds a Connection. If the upper-layer application does not use a Connection any more, StreamAllocation removes one. 3. A background task will periodically clear connections whose StreamAllocation list is empty and maintain five sockets for five minutes. 2. Proxy HTTP: Set the SOCKET IP address to the proxy IP address, and set the socket port to the proxy IP address. 3. HTTP proxies help you perform DNS queries on remote servers, reducing DNS hijacking. If a RealConnection exists in the connection pool, get a RealConnection from it. If a RealConnection does not match, go to the next step. Call platform.get ().connectSocket to select the best socket library under the current Platform Runtime for handshake. 3. Put the established RealConnection into the connection pool cache. 4. Chain of responsibility mode: Cache, retry, establish a connection and other functions exist in the interceptor network request related, mainly network request optimization. Android data layer architecture implementation part 1, Android data layer architecture implementation part 2 3. Okio 1. introduction; 1. Buffer: implements 3, 4 Buffer areas with internal bidirectional linked lists of segments. When transferring data, only Pointers need to be shifted to point. Reduce memory application and data copy 2. Fewer classes, complete functions, and high development efficiency 3. Internal implementation: 2. Share the internal byte array of the Segment to reduce data copy 3. Share and recycle the Segment from the SegmentPool 4. Finally okio is just a encapsulation of Java IO, all operations are based on Java IO write at the end: I admire you for those of you who can see here. This article was put together before the headline interview and I got 80% of the questions right, so good luck.