This article was first published on wechat public number — interesting things in the world, handling reprint please indicate the source, otherwise will be held responsible for copyright. Wechat account: A1018998632, QQ group: 859640274

The last time I wrote this article was almost a year ago. In this year, I went around and around from Android to Java and back to Android. I met with many big companies for school recruitment, such as Alibaba, JINGdong, Xiaomi, Toutiao, Zhihu, Tencent and Youwei, and also got several offers. Thank you for your attention, let me in Jane book also mixed with a Jane book excellent programmer author title, so in order to return to 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 mistakes, if you have any questions, please leave a message or add me to DISCUSS on QQ)

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

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.
  • 6. The width and height after measure() can be obtained in three ways:
    • 1. Get from Activity#onWindowFocusChange()
    • 2. View.post (Runnable) posts the code to the end of the message queue.
    • 3.ViewTreeObservable.

3. Please introduce the loading process of the four android components in detail

  • 1. The loading process of android’s four major components: This is my summary of a blog post

4. The startup mode of the Activity

  • 1. Standard: default standard mode, each startup creates an instance,
  • SingleTop: call onNewIntent if it is at the top of the stack, starting with onResume()
  • 3. SingleTask: stack reuse. As long as this type of Activity is used in the stack, the Activity at the top of the stack will be removed
  • 4. SingleInstance: singleInstance mode. In addition to the 3 features, the system creates a separate stack for the Activity.

A->B->C->D->A->B->C->D ->A->B->C->D

  • 1. This topic requires an in-depth understanding of the startup mode of the activity
  • 2. The final answer is: two stacks, foreground stack is only D, background stack from bottom to top is A, B, C

6. The Activity cache method

  • 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 exits without calling stopService, the Service will continue to 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

  • 1. Improve the service priority
  • 2. Improve the service process priority
  • 3. Restart service in onDestroy

9. What is the difference between static Broadcast and dynamic Broadcast

  • 1. Dynamic is safer than static
  • 2. Static initialization is done when the app starts dynamically using code initialization
  • 3. Static yes Configure dynamic no
  • 4. Lifetime. The lifetime of static broadcast can be much longer than that of dynamic broadcast
  • 5. Priority Dynamic broadcasts have a higher priority than static broadcasts

10. What data types can an Intent deliver

  • 1.Serializable
  • 2. Charsequence: Mainly used to pass String, char, etc
  • 3.parcelable
  • 4.Bundle

11. What are the advantages and disadvantages of Json and the principle of parsing

  • 1.JSON is much faster than XML
  • 2.JSON data is smaller than XML
  • 3.JSON is less descriptive of data than XML
  • 4. The basic principle of parsing is: lexical analysis

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 method is automata and regular expression
  • 2. Grammar analysis: Combine a series of words into a grammar tree. The general implementation methods are top-down and bottom-up
  • 3. Semantic analysis: Context-sensitive reviews of structurally correct source programs
  • 4. Object code generation
  • 5. Code optimization: optimize the generated object code,

13. What kinds of animations are there 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.
  • 4.View property animation:
    • 1. Interpolator: The function is to calculate the percentage of attribute changes based on the percentage of time elapsed
    • 2. Estimator: A class that calculates how many values a property has changed on the basis of one

Handler, Looper message queue model, the role of each part

  • 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 and finish one by one ()

Android IPC:Binder principle ##

  • 1. Binder is used when activities communicate with services.
    • 1. If you belong to the same process, you can inherit Binder and use Service in your Activity
    • 2. If you do not belong to 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). OnTransact () is a method that lets the Proxy make a remote call to the Activity in different processes to implement the Activity operation Service
    • 2. The Proxy class is the Proxy on the Activity side, which has IBinder mRemote(the Binder on the remote side). The implementation of the two interfaces is simply the Proxy that ultimately does the actual operation 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 this process’s SQLite in the add, delete, change, check method, query in other processes), Socket

17. Describe a cross-process communication

  • 1. Client, Proxy, serviceManager, BinderDriver, IMPL, and Service
  • 2. Binder sends a 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 be suspended or not, and there is a keyword oneway to solve this problem

18. Important Terms of Android

  • 1. ActivityManagerServices, hereinafter referred to as AMS, server-side objects, is responsible for all the Activity in the system life cycle
  • 2.ActivityThread, the real entry point of the 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 the Activity
  • 3.ApplicationThread, which implements the 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: application 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).
  • 2. Hierarchical Windows: Windows is applied in 1-99, sub-Windows in 1000-1999, and system Windows in 2000-2999. Windows Manager provides three functions of adding, deleting, and modifying views.
  • 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. There are four lists to store the corresponding View, ViewRootImpl, WindowManger. LayoutParams and the View is to be deleted
  • 5. The entity of the Window exists in the remote WindowMangerService, so adding, deleting and modifying the Window locally is to modify the List above and then redraw the View via ViewRootImpl. Modify the Window remotely using 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. Use LruCache to cache memory.
    • 2. Use DiskLruCache to cache disks.
    • 3. Implement an ImageLoader process: synchronous asynchronous loading, image compression, memory disk cache, network pull
      • 1. Synchronous loading creates only one thread and loads images in sequence
      • 2. Asynchronous loading uses thread pool, so that the existing load tasks are in different threads
      • 3. In order not to start too many asynchronous tasks, only enable image loading when the list is still

21. 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.
  • 2. Jar can be dynamically loaded through URLClassLoader
  • 3.ClassLoader isolation problem The JVM recognizes a class by: ClassLoader ID +PackageName+ClassName.
  • 4. Load public classes in different Jar packages:
    • 1. Make 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 before 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. You can use DexClassLoader to load and access the DEX package in APK
  • 2. How to load resources is a big problem, because the host program does not have resources in apK, so calling R resources will give an error, so we use getAssets() and getResources() in the Activity to 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. Disadvantages:
    • 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 statically registered Broadcast are not supported
    • 3. Implicit calls for activities in LaunchMode and Apk are 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 functions

25. Thread synchronization problem, common thread synchronization

  • 1. Sycn: atomicity, visibility and order are guaranteed
  • 2. Lock: ensure atomicity, visibility and order
    • 1. Spin lock: allows a thread to execute an empty loop instead of being suspended when 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: the thread that does not acquire the Lock waits or suspends, Sycn, Lock
    • 3. Reentrant Lock: a thread can obtain the Lock multiple times, such as Sycn and Lock
    • 4. Pessimistic locking: Every time you try to get data, you think someone else will modify it, so it blocks all other threads Sycn and 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 when I update the data, I will judge whether others have updated the data during this period, and I can use the version number and other mechanisms. cas
    • 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 reads
  • 3.volatile
    • 1. Visibility is guaranteed, not atomicity
    • 2. There are three steps in the increment operation
  • 4.cas
    • 1. Operations: 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 there will be a problem
    • 4. Limitations resolved: add V to version.
  • 5. What is thread insecurity?
    • 1. If one thread writes data and multiple threads read data, the data will be read in half
    • 2. Multi-threaded data writing may cause dirty data

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 pool
    • 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 count
      • 2. Graph search and accessibility analysis
    • 2. Recycling algorithm:
      • 1. Mark clear copy: used for young generation
      • 2. Mark finishing: used in the old days
    • 3. Heap partition:
      • 1. Eden 80% in Youth zone, Survivor1 10%, survivor2 10%
      • 2. The old district
    • 4. Vm stack partition:
      • 1. Local variation scale
      • 2. Operand stack
      • 3. Dynamic linking
      • 4. The method returns the address
    • 5.GC Roots:
      • 1. The object referenced in the VM stack (local variable table in the frame)
      • 2. The object referenced by the class static attribute in the method area
      • 3. Objects referenced by constants in the method area
      • 4. Objects referenced by JNI in the local method stack

27. The 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.
  • 2.HTTP HTTPS difference:
    • 1.HTTPS Uses TLS(SSL) for encryption
    • 2.HTTPS works on TCP port 443 by default
    • 3. Its working process is generally 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 DH algorithm negotiates the symmetric encryption algorithm key and hash algorithm key
      • 4. The SSL encryption tunnel negotiation is complete
      • 5. The web page is transmitted in encrypted way, encrypted with negotiated symmetric encryption algorithm and key to ensure data confidentiality; The hash algorithm is used to protect data integrity from tampering
    • 3. HTTP request package structure, CLASSIFICATION of HTTP return codes, the difference between 400 and 500
      • 1. Package Structure:
        • 1. Request: Request lines, headers, data
        • 2. Return: status line, header, data
      • 2. HTTP return codes are classified into the following categories: Message, success, redirection, client error, and server error
    • 4.Tcp
      • 1. Reliable connection, three handshakes, four waves
        • 1. Three-way handshake: Prevents the server from wasting resources by waiting. For example, if C goes offline after S confirms the two-way handshake, S will waste resources
          • 1. Syn -c = x: indicates that the message is the sequence number of X
          • 2. 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.
          • 3. Ack -c = y + 1 indicates that the SYN-S message is received successfully
      • 2. Four wave: TCP is in full-duplex mode
        • 1. Fin-c = x, indicating that c to S needs to be closed. Ack -c = y, indicating 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 is approved to be closed
        • 3. Fin -s = y + 1, indicating that S is ready to shut down, waiting for the last command from C
        • Ack -c = y + 1; ack-c = y + 1
      • 3. Slide the window to stop waiting, back up, and 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

  • 1. The process
    • 1. Aapt generates R files
      • 2. Aidl generates Java files
      • 3. Compile all Java files into class files
      • 4. Merge all class files and third-party packages into a dex file
      • 5. Integrate resources, SO files, and DEX files into APK
      • 6. Apk signature
      • 7. Align apK bytes
  • 2. Contents: SO, dex, Asset and resource files

30 network hijacking type principle: you can baidu to understand the specific concept

  • 1.DNS hijacking, spoofing, and contamination
  • 2. 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, and subclass loading
  • 2. Verification: Verify the correctness of file format, metadata, bytecode, and symbol reference
  • 3. Load: get the file byte stream according to the full class name, put the byte stream into the method area as static storage structure, and generate the class object
  • 4. Preparation: Partition memory on the heap for static variables
  • 5. Parse: Convert symbolic references in the constant pool to direct references
  • 6. Initialization: Initialize static variables
  • 7. Book recommendations: In-depth understanding of Java Virtual machine, blog recommendations: Java/Android interview JVM part of the understanding

32. The retrofit

  • 1. Dynamic proxy Creates a proxy class for an interface
  • 2. Use reflection to parse annotations of each interface and construct HTTP requests with input parameters
  • 3. Obtain the returned HTTP request and use Adapter to parse it into the required return value.

33. How to store the bundle’s data structure

  • 1. Key-value pair storage
  • 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. When a Bundle passes objects or arrays of objects, the Serializable or Parcelable interfaces must be implemented

Click butTom inside the ListView and move the event stream

  • 1. When pressing the button:
    • Activity >phoneWindow–>ViewGroup–>ListView–> Botton –>phoneWindow–>ViewGroup–>ListView–> Botton
    • 2. Without interception, the event arrived at the button. In the process, a list of views for event delivery was established
    • 3. Go to button’s dispatch method — onTouch–> View is available –>Touch agent
  • 2. Move the button when clicking:
    • 1. Generate a move event, which will be intercepted in the listView
    • 2. The listView will consume the slide event
    • 3. Subsequent slides are consumed by the listView
  • 3. Finger up: the front to establish a list of views, the parent of the listView in the acquisition of events, will directly take the list of listView for its event consumption.

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. The communication modes of operating system processes are shared memory, socket, and pipe

37. Difference between operating system processes and threads

  • 1. In short, a program has at least one process, and a process has at least one thread.
  • 2. The dividing scale of thread 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. There are multiple threads as multiple independent applications to achieve process scheduling and management and resource allocation

38. Implementation of a HashMap: Capacity is the number of buckets, and Load factor is the maximum proportion of buckets that are full. 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. Put the process
    • 1. Hash key hashCode(), then calculate 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. Replace old value if the node already exists
    • 6. If the bucket is full (exceeding the load factor*current capacity), resize.
  • 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, it is simply a matter of doubling the bucket, recalculating the index, and placing the node in the new bucket
  • 4. Get process
    • 1. Calculate the array table based on the hash of the key
    • 2. Use equals to traverse the linked list for comparison

39. MVC, MVP, 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. Circular dependencies
    • 1. The Activity is heavy and difficult to unit test
    • 2. Serious coupling between View and Model
  • 2. MVP: Data, View, Presenter. The View gives operations to the Presenter, the Presenter gets the data, the data gets back to the Presenter, the Presenter refreshes the View. PV, PM bidirectional dependence
    • 1. The interface explodes
    • 2. The Presenter is very heavy
  • 3. MVVM: Data, View, ViewModel, View will operate to ViewModel, ViewModel to get data, data and interface binding, data update interface update.
    • 1. The business logic of the viewModel can be tested separately
    • 2. A View for a viewModel business logic can be separated, there will be no omnipotent class
    • 3. Data and interface binding, no need to write garbage code, but reuse uncomfortable

40. How are Java threads implemented

  • 1. The Thread of inheritance
  • 2.Runnale
  • 3.Future
  • 4. The thread pool

41. How ArrayList removes duplicate elements or specified elements;

  • 1. Delete the duplicate: Set
  • 2. Delete the specified: iterator

42. How to design 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.
  • 3. Udp-based reliable transmission protocols include RUDP, RTP, and UDT

43. Why can inner classes access outer 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

44. Design the function of contact storage and query on mobile terminals, which data structures 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 red node must be followed by the black node
  • 3. The number of black nodes in each path from root to leaf is the same

46. Linux Asynchronous and synchronous I/O:

  • 1. Synchronization: For the client, the client waits but does not suspend: the main thread is called
  • 2. Asynchronous: For the client, the client initiates a request and calls back the service when it is ready
  • 3. Blocking: For a Service, the service side is suspended while preparing the IO until it is ready and then wakes up the 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 and performs operations after the preparation is complete: NIO, Linux SELECT, poll, and epoll
  • 4. Multiplexing IO: An optimization for non-blocking IO, Java NIO, 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.
    • Asynchronous IO requires low-level operating system support, that is, kernel support. Java 7 provides Asynchronous IO

47. The internal implementation of ConcurrentHashMap and the implementation of HashTable were abandoned for the following reasons:

  • 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. The IntentService is what

  • 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. Reduces I/O operations and improves class lookup speed

51. Memory leak

  • 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.
  • 3. Stop the thread when the activity stops, or unregister the Listener
  • 3. Use weak references, so that even if the Listener holds the activity, it will still be reclaimed during GC
  • 4. The tools: LeakCanary

52. Overdrawing, Caton optimization:

  • 1. Overdraw:
    • 1. Remove the Windows default Background: getWidow setBackgroundDrawable (null);
    • 2. Remove unnecessary Background from the XML layout file
    • 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. The introduction of layout file inside, can replace LinearLayout with the merge, the outermost layers RelativeLayout, when this UI elements cohesion in the include location directly
    • 5. Tools: HierarchyViewer Views the view hierarchy
  • 2. Caton optimization: 16ms data update

53. Apk thin body:

  • 1. Classes. dex: Optimize this file by obfuscating the code and removing unnecessary jars and code
  • 2. Resource files: Use Lint to scan for static resources that are not used in your code
  • 3. Picture resources: Using Tinypng and webP, the following details the picture resource optimization scheme, vector map
  • 4. Remove unnecessary SO files. Currently, mainstream apps usually only put an ARM SO package

54. The formation of ANR, what is the time limit for the occurrence of ARN on each component

  • 1. As long as the main thread time-consuming operations, ARN, such as IO
  • 2. Broadcast timeout is 10 seconds. The timeout period for no response to keys is 5 seconds

55. Difference between Serializable and Parcelable

  • 1.P consumes small memory
  • 2. Network transmission with S program using P
  • 3.S Facilitates data persistence
  • 4.S uses reflection to trigger garbage collection slowly

56.Sharedpreferences

  • 1. XML key-value pairs stored on hard disks may cause performance problems if there is too much data
  • 2.ContextImpl records important SharedPreferences data, file path, and instance key-value pairs
  • 3. The read operation is blocked until the XML file is fully loaded into memory. After the XML file is fully loaded into memory, the data in memory is directly read
  • 4. Since the apply is asynchronous and has no return value, the commit is synchronous and has a return value to know whether the change was committed successfully
  • 5. When multiple concurrent commit requests are submitted, the commit requests continue to be executed only after the commit data being processed is updated to disk files, 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.
  • 6. Blog recommendations: A comprehensive analysis of SharedPreferences

How does the operating system manage memory:

  • 1. Use registers to map the process address to physical memory
  • 2. Virtual memory Map memory to hard disks to increase memory size
  • 3. Virtual memory is used for memory paging management
  • 4. Page table to achieve paging, 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. Blog recommendation: Chapter notes on modern operating systems

58. What happens when the browser returns an address

  • 1. The DNS
  • 2. A TCP connection
  • 3. Send an HTTP request
  • 4. The server processes the request and returns an HTTP packet
  • 5. The browser parses the rendered page
  • 6. The connection ends

59. When does Java generic type erasure occur and what is important about wildcards?

  • 1. This occurs at compile time
  • 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. Blog recommendations: Effective Java Notes (not including deserialization, concurrency, annotations, and enumerations), Android Ali Interview Java Basics

60. The 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 after accidental destruction, and restoreInstance is called after restoration. 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

  • 1. Quick sorting, heap sort first various sorting algorithms
  • 2. Various operations of linked list: judge ring formation, judge intersection, merge linked list, count down K nodes and search for link points
  • 3. Binary tree, red-black tree, B-tree definition and time complexity calculation method
  • 4. Dynamic programming, greedy algorithms, simple graph theory
  • 5. Recommended book: Introduction to Algorithms, including previous examples of graph theory

62. The process of starting another process:Start an app

63. Open source framework source

  • 1.Fresco
    • 1. The MVC framework:
      • 1.Controller Indicates the explicit Drawable of data displayed in Hierarchy
      • 2.ImagePipeline is responsible for data acquisition in Controller, and the data returned is CloseableImage
      • 3.Drawee assigns all operations except initialization to Holder, who holds Controller and Hierarchy
    • 2.Drawable hierarchy and drawing:
      • 1. To draw a Drawable, call invalidateSelf() to trigger onDraw().
      • 2.Drawable is divided into: container class (save some Drawable), self-drawing class (progress bar), graph transformation class (scale, rotate, matrix transformation), animation class (internal constantly refresh, webP and GIF frame drawing).
      • 3. The CloseableImage returned by ImagePipeline is resolved to a Drawable by a single DrawableFactory
      • 4. Webp and GIF animations are parsed by JNI code, while 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 Sumer — encoding image memory cache consumer — write hard disk cache consumer — image data
    • 4. Memory cache:
      • 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, items are removed from the Map of items to be destroyed until the cache size matches the configuration.
      • 2. The reference count here is a reference counter implemented with the Fresco component.
      • 3. The cache has a proxy class that tracks cache access.
      • 4.CountingLruMap uses LinkedHashMap to store data.
    • 5. Hard disk cache:
      • 1.DefaultDiskStorage uses the Lru policy.
      • 2. To prevent all files from being concentrated in one file, create multiple folders with different names and use the hash algorithm to disperse the cache files
      • 3.DiskStorageCache encapsulates DefaultDiskStorage. Not only does it cache access tracking, but it also maintains a

        key-value pair in memory. I’m gonna have to check the hard drive again.
        ,value>
      • 4. Deleting the cache of a hard disk occurs only when the data size of the hard disk exceeds the upper limit. In this case, keys in the cache are also deleted.
      • 5. Insert hard disk data in the form of an insert device. 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 file suffix is.temp, which is changed to make the file visible to the client only after a call to commit().
      • 6. Use the FileTreeVisitor provided by Java to traverse files
    • 6. Object Pool
      • 1. Use arrays to store a bucket with a Queue inside the bucket. The array subscript is the byte size of the data application memory, and the Queue inside the bucket is the memory block. So arrays use sparse arrays
      • 2. Memory can be allocated in two ways: (1) memory allocated on the Java heap; (2) memory allocated on the local ashme
    • 7. Design patterns: Builder, Chain of Responsibility, Observer, Agent, Composition, Share, Adapter, Decorator, Strategy, Producer consumer, Provider
    • 8. Custom count references: similar to c++ smart Pointers
      • 1. Use a static IdentityHashMap < to store the number of times an object needs to be referenced by count >
      • 2. Add a SharedReference to the object to be referenced, a destructor to destroy the resource, and a static factory method to copy your own object. Add one to the reference count. Provides a method to destroy itself, indicating that it needs to become an unreferenced object, in which case the reference count is reduced by one.
      • 3. When the reference count returns to zero, the destroyer will destroy the resource, such as bitmap recycle memory or JNI memory by calling JNI methods to return the memory.
    • 9. Blog recommendations: Starting from scratch with a Fresco hard disk cache, starting from scratch with a Fresco GIF and Webp animation, starting from scratch with a Fresco internal cache, starting from scratch with a Fresco summary
  • 2. OKhttp:
    • 1. Synchronous and asynchronous:
      • 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:
      • A Connection encapsulates a socket. A ConnectionPool stores all connections. StreamAllocation is a unit of reference count
      • 2. When a request obtains a Connection, a StreamAllocation is passed in. The Connection contains a list of StreamAllocation weak references. StreamAllocation will add one. If the upper-layer application is no longer in use, it will delete one.
      • 3. A background task will periodically clear connections whose StreamAllocation list is empty in the ConnectionPool. Five minutes to maintain five sockets
    • 3. Select routes and establish connections
      • 1. There are two ways to choose a route:
        • 1. If there is no proxy, the local DNS is used to find the IP address. Notice that the result is an array, that is, a domain name has multiple IP addresses, which is the source of automatic reconnection
        • 2. Proxy HTTP: Set the SOCKET IP to the proxy IP address and the socket port to the proxy IP address
        • 3. Proxy benefits: HTTP proxy will help you perform DNS queries on remote servers, which can reduce DNS hijacking.
      • 2. Establish a connection
        • 1. If a RealConnection exists in the connection pool, get the RealConnection from it. If not, go to the next step
        • 2. According to the selected Route, 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. If TLS exists, the SSL version is used to secure the handshake with the certificate
        • 5. Construct the HttpStream and maintain the socket connection
    • 4. Chain of responsibility mode: functions such as caching, retry and establishing connections exist in interceptors related to network requests, mainly network request optimization. Problems encountered during network requests
    • 5. Blog recommendation: Implementation of Android data layer architecture first, implementation of Android data layer architecture second
  • 3.okio
    • 1. Introduction;
      • I sink with myself
      • 1. 2. Smart water bottle
      • 3.BufferSink: sink with cache area
      • 4.BufferSource: source with cache area
      • 5.Buffer: Implements 3 and 4 Buffer areas with bidirectional linked lists of segments. When transferring data, only Pointers need to be moved to point
    • 2. Advantages over Java IO
      • 1. Reduce memory application and data copy
      • 2. Less classes, complete functions, high development efficiency
    • 3. Internal implementation:
      • 1.Buffer Segment bidirectional linked list to reduce data copy
      • 2. Share the internal byte array of the Segment to reduce data copy
      • 3. Share and recycle segments from SegmentPool
      • 4. Buffer is actually operated in sink and source. Buffer can act as sink and source
      • 5. Ultimately okIO is just a wrapper around Java IO, all operations are based on Java IO

Write at the end: I admire you for seeing people here. I put this article together before the headline interview and ended up hitting **80%** of the questions, so good luck.

No angst peddling, no clickbait. Share some interesting things about the world. Topics include but are not limited to: science fiction, science, technology, the Internet, programmers, computer programming. The following is my wechat public number: Interesting things in the world, dry goods waiting for you to see.