How many launch modes does an Activity have? What are the characteristics of each?
  1. Standard (default startup mode)

    When we launch the Activity with an intent, a new instance of the Activity is always created.

  2. SingleTop (Top of stack reuse)

    If you want to start an Activity that exists at the top of the stack, instead of creating a new instance of the Activity, the onNewIntent() method of the Activity is called to prevent repeated creation of the Activity at the top of the stack. If an instance of the invoked Activity already exists but is not at the top of the stack, the invoked Activity will still be created.

  3. SingleTask (in-stack reuse)

    An Activity only has one instance in the task stack. If the Activity you want to start already exists in the Task stack, instead of creating a new instance of the Activity, you reuse the existing Activity by calling onNewIntent(), And clear all other activities on the Activity task stack

  4. SingleInstance (singleInstance pattern)

    An Activity with this mode can only be in a single task stack, not other activities, and any other activities started from that Activity will be placed in the other task stack.

How many types of services are there? What are the application scenarios?
methods Start the way Stop the way Method of communicating with started components The life cycle
startService The service is started when the startService() method is called in the other component The service stops running when the stopSelf() method is called within a service, or when the stopService() method is called by another component The default communication mode is not provided, and the service runs independently after it is started Once started, a service can run in the background indefinitely, even if the component that started it has been destroyed, until it is stopped
bindService The service is started when the bindService() method is called in the other component The service will stop running after all components bound to the service are destroyed or they all call the unbindService() method With ServiceConnection, components can interact with services, send requests, get results, and even perform these operations across processes using IPC The service stops when all its bound components are unbound (either because the component has been destroyed or because it called the unbindService() method)
How many ways are there to register for broadcast? What’s the difference?
  1. Registration code

    Non-resident registration, following life cycle changes, and unregistration when the Activity is not visible. However, when a BroadcastReceiver (Receiver) needs to update its UI, it usually uses this method to register broadcasts

  2. Register via androidMainfest.xml

    Resident line registration, in simple terms, even if the application is closed, the background receives a message notification, still can wake up the application in the response program

What life cycle callbacks do activities have?
methods Introduction to the
onCreate SetContentView (int layoutResID)findViewById(int ID) (ps: setContentView(int layoutResID)findViewById(int ID) This method returns null if the fragment is a control inside the fragment, and the Bundle is executed after the fragment.) The Bundle parameter can be used to restore the state data that was held before, and is used when switching between horizontal and vertical screens. This method call is typically followed by an automatic onStart() call
onRestart This method is called when an Activity in the Stopped state is called again. Such as when the user is returned from another Activity.
onStart Execute this method before the activity is brought to the foreground and visible. Called after onCreate is created or after onRestart is restarted. After this method is executed, onResume() is automatically called in normal cases, or onStop() may be directly called in abnormal cases.
onResume When this method is called, the Activity is foreground visible and interactive, and the Activity is in the running state
onPause The Activity executes the method before it is covered by another Activity; The Activity is Paused and was killed by the system in extreme cases in versions prior to 3.1. This method can be used to save persistent data, stop animations, and other CPU-consuming things, and can only be used for lightweight, fast operations. OnStop is a better place to perform time-consuming operations
onStop Perform this method when the Activity is completely invisible, such as when a new Activity starts and overwrites the current Activity, or when it returns to the previous Activity. The Activity is currently Stopped and can be destroyed by the system at any time, or it can be restarted and brought to the foreground. In exceptional cases, the method may not execute and the Activity will be killed
nDestroy The last method to execute before an Activity resource is reclaimed by the system. Called when you call Finish () or when the system temporarily destroys the Activity. You can use isFinishing() to determine if it is being destroyed normally or if it is an exception. When the user changes Settings (screen orientation, language, input device, etc.), the current Activity instance is destroyed and a new instance is created. In exceptional cases, the method may not execute and the Activity will be killed
What are the extension functions in Kotlin

The extension function in Kotlin actually adds a static final method to its own class, passing the class to be extended as the first argument to the method, and then using:

fun String.hello(str: String): String{
    return "hello" + str + this.length
}

fun String.hello1(str: String): String{
    return "hello$str"
}
Copy the code

After decompiling, the bytecode is generated as follows

public final class ExtensionTestKt { @NotNull public static final String hello(@NotNull String $receiver, @NotNull String str) { Intrinsics.checkParameterIsNotNull($receiver, "$receiver"); Intrinsics.checkParameterIsNotNull(str, "str"); return "hello" + str + $receiver.length(); } @NotNull public static final String hello1(@NotNull String $receiver, @NotNull String str) { Intrinsics.checkParameterIsNotNull($receiver, "$receiver"); Intrinsics.checkParameterIsNotNull(str, "str"); return "hello" + str; }}Copy the code

The extension functions in Kotlin are actually implemented by adding public static final functions to the class, which reduces the use of the utils class.

Extension functions are statically parsed and handled using a process of static dispatch. This means that the extension function called is determined by the type of the expression on which the function is called, not by the result of the expression’s run-time evaluation. The meaning is in the use of the extension function, if the class itself and its subclasses are the expansion of the same function, this function will not have to rewrite the relationship, at the time of use, will only depending on the type of the object’s actual need to use this method to decide which one is called, is equivalent to call a static method. Instead of dynamic dispatch.

What is the JVM memory model like?

The method area and heap are shared by all threads, while the stack, local method stack, and application virtual machine are thread private.Copy the code
  • Program counter
A program counter is a small memory space that is private to the thread and can be considered a line number indicator for the current thread.Copy the code
  • Java stack (Virtual machine stack)
The same counter is thread-private and has the same life cycle as the stack, which describes the memory model in which Java methods are executed. When each method is executed, a stack frame is created to store information about local variables, action stacks, dynamic links, method exits, and so on. Each method called corresponds to a stack frame moving from the virtual machine stack to the virtual machine stackCopy the code
  • Local method stack
Local method and the virtual machine is stack is very similar to the role of, the difference is a Java virtual machine stack are executable method (i.e. bytecode) service, while the local method stack service for virtual machine to use native methods, may be the underlying call c or c + +, we open the JDK installation directory can see there are a lot of files written in c, Probably the C code that native methods callCopy the code
  • The heap
The heap is the largest area of memory managed by the Java VIRTUAL machine, and because objects in the heap are shared by threads, synchronization is also required for multithreadingCopy the code
  • Methods area
The method area, like the heap, is an area of memory shared by all threads and is called non-heap to distinguish the heap. Used to store class information, constants, and static variables that have been loaded by the virtual machine. Static variables, for example, are loaded into the method area when the class is loadedCopy the code
GC collection algorithm?
  1. Mark-clear algorithm

    The algorithm is marked first and then cleared. All algorithms that need to be recycled are marked and then cleared. The disadvantages of this algorithm are: low efficiency; A large number of discrete memory fragments can occur after the tag is cleared, which can cause storing large objects to trigger GC collection, resulting in wasted memory and time consumption.

  2. Replication algorithm

    The replication algorithm divides the available memory into two parts, uses one piece at a time, and when the piece is reclaimed, copies the unreclaimed memory to the other piece, and then cleans up the used memory. This algorithm is simple to run and solves the fragmentation problem of mark-clear algorithm. However, this algorithm costs too much, and the available memory needs to be reduced by half. When the object survival rate is high, continuous replication work is required and the efficiency is relatively low.

  3. Mark-collation algorithm

    Tag sorting algorithm for replication algorithm in object survival rate is higher when the last copy to the shortcomings of low efficiency was improved, the algorithm is based on marker – clear, clear not directly, but objects that survive to the end, and then remove one end borders of memory, can avoid discontinuous space already so, You can also avoid continuous replication when the object has a high survival rate. This algorithm is suitable for old generation.

  4. Generational collection algorithm

    The generation collection algorithm is the recycling algorithm currently used by virtual machines. It solves the problem that mark collation is not applicable to the old age. It divides the memory into different ages and uses different algorithms in different ages so as to use the most suitable algorithm. However, the old age object has a high survival rate and there is no extra space to guarantee its allocation, so the marker collation algorithm is used

Memory allocation and reclamation policies

The diagram for memory allocation in the heap is shown in the figure. When an object is created, the region will be allocated in Eden region first. If the memory is insufficient, the older region will be transferred to Survivor region, and when Survivor region is insufficient, the older generation will be transferred. For some static variables that don’t use objects, those that are called directly will be put into the immortal generation. Generally speaking, objects that live for a long time will eventually be stored in the aged generation. There is also a special case that will be stored in the aged generation. When creating large objects, such as data, which need to apply for continuous space, if the space is large, the objects will be directly stored in the aged generation.

In the recycling process, there is a more important parameter, is the age of the object, if the object is used in a garbage collection process, the age of the object will be increased by 1, otherwise, minus 1, when the count is 0, the recycling, if the age reaches a certain number, the old generation. In general, the memory allocation mechanism is mainly reflected in whether the object is still in use after creation. If the object is no longer in use, it will be recycled. If the object continues to be in use, its age will be updated to a certain extent and transferred to the old generation.

How many reference types are there in Java?
  1. Strong reference

    For example, String strong = new String(” strong Reference”). When an instance object has a strong Reference, the garbage collector will not reclaim the object. When memory is insufficient, the garbage collector will not collect the object. It would rather throw an OutOfMemeryError than recycle a strongly referenced object. Because the JVM thinks that a strongly referenced object is an object that the user is using, it can’t tell which one to recycle, and forcible collection can lead to a serious system error

  2. Soft references

    If an object has only soft references, then the JVM will only reclaim the object if it runs out of memory, and not otherwise. Soft references can be used in conjunction with the ReferenceQueue, and when the soft-referenced object is reclaimed due to lack of system memory, the JVM adds the soft reference to its associated ReferenceQueue.

  3. A weak reference

    Only weakly referenced objects are reclaimed when the JVM triggers gc. Unlike soft references, weak references are reclaimed whether they are out of memory or not. Weak references can be used in conjunction with the ReferenceQueue. When a soft reference object is reclaimed because the system triggers a GC, the JVM adds the weak reference to the ReferenceQueue associated with it, but because garbage collector threads are of low priority, weak references may not be reclaimed quickly.

  4. Phantom reference

If an object is referred to only by a virtual reference, the garbage collector can reclaim it at any time. The virtual reference is used to track the activity of the object being reclaimed by the garbage collector, and when reclaimed, the JVM adds the virtual reference to its associated ReferenceQueue. Unlike soft and weak references, virtual references must have a ReferenceQueue associated with them, which is null via PhantomReference.get ()

How does Android messaging work?

  • The Handler sends a Message to the MessageQueue queue via sendMessage();

  • Through loop(), Looper continuously extracts the Message that meets the trigger condition and sends the Message to Target for processing.

  • After dispatchMessage(), it is passed back to Handler’s handleMessage() for processing accordingly.

  • When Message is added to a MessageQueue, characters are written to the pipe to wake up the loop thread; If MessageQueue has no Message and is Idle, methods in the IdelHandler interface are executed, often to do some clean work.

How are Android touch events passed?

  1. onInterceptTouchEventThe return value true indicates event interception,onTouch/onTouchEventThe return value true indicates event consumption.
  2. The touch event is handed over firstActivity.dispatchTouchEvent. And then it goes down, and when none of the viewgroups in the middle intercepts, it goes to the bottom View, and it starts from the bottom ViewOnTouchEventIf it never consumes, it finally returns toActivity.OnTouchEvent.
  3. ViewGroup isonInterceptTouchEventInterception method. In the distribution process, any intermediate ViewGroup can intercept the interception directly. In this case, the interception is sent to the ViewGroup that intercepts the interceptionOnTouchEventTo deal with.
  4. The child View can be calledrequestDisallowInterceptTouchEventMethod to setdisallowIntercept=trueTo block the parent ViewGrouponInterceptTouchEventIntercept operations.
  5. When OnTouchEvent bubbles from bottom to top, if OnTouchEvent of any middle layer consumes the event, it will not be passed up, indicating that the event has been processed.
  6. If the View does not consume ACTION_DOWN events, subsequent ACTION_MOVE events will not be received.
  7. As long asView.onTouchEventIs clickable or long press, then consume the event.
  8. onTouchPrior to theonTouchEventExecution, omitted from the flowchart above,onTouchThe location ofonTouchEventThe front. whenonTouchIf true is returned, it is not executedonTouchEventOtherwise, onTouchEvent is executed.onTouchOnly the View is setOnTouchListenerThe method is executed only when the value is enable.
How are Android views drawn?
How does Android communicate between different components? (Across processes, across threads)
The Activity startup process?
AMS, PMS, WMS creation process?
RecyclerView cache mechanism?
To do a 1MB x 10 frame animation, what is the best way to optimize memory?
How do I prevent the search box from making requests too frequently?
How to implement barrage?
How to design the broadcast room gift queue?
What aspects should be paid attention to when designing an image asynchronous loading component?