Several launch modes for an Activity

The startup mode of an activity can be used in several different scenarios.

Standard: This is the default Android mode for starting an Activity. Each Activity is instantiated and the newly created Activity is placed at the top of the stack.

SingleTop: If the current Activity is at the top of the stack, then the Activity will be reused and the onCreate method will not be repeated. Instead, the onNewIntent method will be used directly. If it is not at the top of the stack, it will be used as standard. If the activity is already in the foreground and A push message comes, and you don’t want the activity to be created again to receive the push message, you can use this launch mode. If the activity was A–>B–>C and the push message was A–>B–C, C does not create it again, but instead calls C’s onNewIntent. If the activity is now on the stack A- >C- >B and the push message is started again, it will be A- >C- >B- >C.

SingleTask: This is even worse than singleTop, which always holds one in the Activity stack, whether it is at the top of the stack or not. This startup mode is more straightforward than singleTop. For example, if you have A–>B–>C– D in the activity stack before you open B again, all activities above B will be removed from the activity stack. The acitivity below is still left alone, so the stack is A- >B, which is usually used for the main page in projects.

SingleInstance: This is rarely used, mainly because the activity is always in a single stack. Once an instance of an activity in this mode already exists in a stack, any application that activates the activity will reuse the instance in the stack, preventing multiple tasks from sharing an activity. The rest is basically the same as the singleTask above.

The above various startup modes are mainly through the configuration manifest file, common also can set flag in the code to achieve the above function:

FLAG_ACTIVITY_CLEAR_TOP: In this case, the acivity on the stack can only be empty and it will be created again. If there is A- >B- >C in the current stack, the stack will be changed to A- >B after restarting B, but B will be created again without using B’s onNewIntent method. This is where FLAG_ACTIVITY_CLEAR_TOP comes in handy, clearing the activity on the stack but recreating it itself. If you add FLAG_ACTIVITY_SINGLE_TOP to the onNewIntent, then you don’t want to create B again. The combination of the two is equivalent to the above singleTask mode. FLAG_ACTIVITY_SINGLE_TOP is indistinguishable from singleTop if you use it alone.

FLAG_ACTIVITY_CLEAR_TOP+FLAG_ACTIVITY_SINGLE_TOP=singleTask, the activity to be opened will not be rebuilt, just go to onNewIntent.

FLAG_ACTIVITY_SINGLE_TOP=singleTop

FLAG_ACTIVITY_NEW_TASK

  • In the same taskAffinity case: starting an activity has no effect.

  • Under different taskAffinity: If you start an activity in a stack that already exists in one stack, you cannot start the activity because it already exists in the stack. If the activity to be launched does not exist in the stack, the acvitity is launched and the activity is added to the stack.

FLAG_ACTIVITY_NEW_TASK is used with FLAG_ACTIVITY_CLEAR_TOP, And the taskAffinity of the activity to be launched is different from the taskAffinity of the current activity, which will have the same effect as singleTask because the activity to be launched is not in the same taskAffinity as the original activity. So you can start the activity. It’s a little convoluted here. Here’s a simple formula:

  • FLAG_ACTIVITY_NEW_TASKThis only works if you start the same activity with a different taskAffinity.
  • FLAG_ACTIVITY_NEW_TASKandFLAG_ACTIVITY_CLEAR_TOPIf the activity to be started is in the same taskAffinity as the current activity, the effect will remain unchangedFLAG_ACTIVITY_NEW_TASKIt’s the same effect.
  • FLAG_ACTIVITY_NEW_TASKandFLAG_ACTIVITY_CLEAR_TOPTaskAffinity will have the same effect as singleTask only if the activity is not launched in the same way as the current activity.

FLAG_ACTIVITY_CLEAR_TASK

  • In the same taskAffinity case: andFLAG_ACTIVITY_NEW_TASKWhen used together, starting the activity has no effect.
  • In different taskAffinity cases: andFLAG_ACTIVITY_NEW_TASKWhen used together, if the activity to be started is not already in the stack, start the acitivity and add the activity to the stack. If the activity is already in the stack, remove it from the current stack before adding it to the new stack.

FLAG_ACTIVITY_NEW_TASK+FLAG_ACTIVITY_SINGLE_TOP Is used when pushing a message into an activity while the app is running. If you are currently in that activity, This triggers the activity’s onNewIntent.

FLAG_ACTIVITY_NEW_TASK+FLAG_ACTIVITY_CLEAR_TOP is used when the app is not running to start the activity on the home page, and then jump to the corresponding activity in the corresponding activity.

Android messaging

The messaging mechanism describes how Handler, Looper, MessageQueue, and Message work together.

  • Handler is used to process messages and receive messages. The creation of handler is accompanied by the creation of looper and MessageQueue in handler. Handler depends on Looper, and Looper depends on MessageQueue. Handler is used in the child thread because the child thread has not initialized the Looper object, whereas the main thread has initialized the looper object in the ActivityThread, so it can get the handler directly in the main thread.

  • Looper is used to poll for messages. In other words, the loop method is used to implement an infinite loop. When there is a message, the message is retrieved through messagequue. The handler gets the message when it has a message and passes it to the handler. If there is a callback in the message, the handler will call it directly. Otherwise, the handler will handle it through handleMessage.

  • MessageQueue is a single linked list structure to store messages. After fetching the Message through the next method, message.next is sent to the current Message, and message.next=null. Essentially removing the current message. But in looper, every time a message is fetched from next, it is put into the sPool of Message, which is cached for easy use.

  • Message stores the obJ and WHAT that we use a lot, as well as the target and callback that we don’t care about.

The question is, how many loopers does a thread have, how many handlers, and where does a Looper live in a thread?

One Looper per thread, which can have multiple handlers, is stored in the thread’s ThreadLocal object, which is the thread’s cache

ThreadLocal: ThreadLocal is used as a Thread variable, as seen in the Thread class. ThreadLocal is a wrapper around ThreadLocalMap that implements the GET and set methods. ThreadLocalMap is actually an array of Entry classes that inherit from weak applications. Weak references contain the current object of ThreadLocal. The value of the Entry stores the object to be stored by the current thread, and the value is the member variable of the Entry. The Entry object in ThreadLocalMap stores a weak reference to the ThreadLocal, and the value directly acts as a strong reference to the Entry. To prevent memory leaks, manually call the remove method.

IntentService

IntentService is a Service that Google creates child threads on top of a native Service. IntentService is a service designed for Android developers to implement time-consuming operations within a service. We can override onHandleIntent to perform a callback for a time-consuming operation. IntentService will automatically destroy itself after the time-consuming operation is completed. IntentService can be started multiple times to perform multiple tasks, whereas IntentService is created only once. Only the onStart method is triggered each time it is started. Internally, the Handler realizes the process of asynchronously processing time-consuming operations. It is generally used in Service to process time-consuming operations.

Question: Why can IntentService implement time-consuming operation?

  • In onCreate, we start a thread with a HandlerThread, and the HandlerThread is a little bit different from the Handler we normally use, we create a looper object in the run method, So HandlerThread allows IntentService to use handler in child threads to achieve time-consuming operations.

HandlerThread

HandlerThread is also a Thread, but it is wrapped around the Handler carrier, and creates a Looper object in the run method. This is why you can use HandlerThread directly in IntentService. We know that a thread can have more than one handler, so it’s more convenient to use HandlerThread. We don’t need to worry about the creation of a handler.

Dispatching events

Event distribution can be divided into three parts: distribution, interception and consumption; When we touch the screen, by default we’re going to distribute the Activity, then we’re going to distribute the ViewGroup, then we’re going to intercept the ViewGroup, then we’re going to distribute the View, then we’re going to consume the View, and if the View doesn’t consume, And then it goes back to the ViewGroup’s consumption event, and if the ViewGroup doesn’t consume either, it goes back to the View’s consumption event. The entire event distribution constitutes a U-shaped structure, and the detailed flow of the distribution is summarized below:

  • If a ViewGroup dispatchTouchEvent returns true or false, the touch event will not be passed to the child view, false will only trigger action_DOWN, and the ViewGroup onTouchEvent will not be triggered. The touch event is only passed to the child view if super.dispatchTouchEvent is returned.
  • If the ViewGroup onInterceptTouchEvent. Return false or super onInterceptTouchEvent, touch event is passed to the view. The event that returns true is not passed down and is handled by its own ontouchEvent.
  • If the view dispatchTouchEvent returns true or false, the touch event will not be passed to its own ontouchEvent event. If the view dispatchTouchEvent returns false, only action_DOWN will be raised. Move and UP will not be raised. Return true to trigger move and UP. Return super.dispatchTouchEvent before the touch event is handed over to its own onTouchEvent.
  • If ontouchEvent returns false, there will only be action_down events, touch events will only be processed by the upper layer, and will only be consumed if true. The event will not be passed up. If super.ontouchEvent is returned, Depending on whether clickable returns true.

This is going to ask about conflict of events, right?

Events follow a principle, is to see if he has event consumption. For example, a LinearLayout has a Button inside it, so clicking on the LinearLayout will trigger the Button. It depends on whether the LinearLayout has the click event set. If so, it will not be transmitted to the Button, and if not, it will be transmitted to the Button.

Android performance optimization, memory optimization

Performance optimization: we can start from interface, APK slimming, confusion, DEX subcontracting, plug-in dynamic loading module, open screen cold start

Interface optimization: Merge can be used to create View stubs. Merge can be used to extract common layouts. Merge can be used to reduce layout levels. Reduce the occupancy of space, constraint layout can reduce the layout of the level, two can improve the efficiency of development, in the custom view view drawing process do not do initialization operation, generally placed in the initialization method of view.

Apk Slimming: You can use The Android Studio lint tool to detect resource files, etc

Obfuscation: can reduce file size, this can be tried in practice, after obfuscation can decompile to see the contents of the APK package

Dex subcontracting: The structure of THE APK package is changed. If the number of methods in the DEX package exceeds the maximum number, subcontracting is required

Plug-in: mainly used in Java dynamic proxy mode and reflection of the idea, the use of Android activity start process, through the dynamic proxy mode dynamic load we need to plug-in activity

Open screen cold boot: The open screen cold boot is mainly optimized for MultiDex startup. Before 5.0, dex subcontracting is not handled, so you need to use multidex. install for compatibility with earlier versions. Mutidex. install obtains the dex package from APK, compresses it into a corresponding ZIP file, converts the dex file into a DexFile object through reflection, and reflects the replacement array. So we can optimize it by determining if the JVM does not support dex subcontracting and start an activity that listens for mutidex. install by listening for mutidex. install. Wait until the mutidex.install processing is complete before processing the normal logic.

Memory optimization

Memory optimization usually refers to running out of memory. The main problem is that the resource should be released and not be collected in time by the GC processor. Usually, animation, context objects, EventBus, AsycTask, Handler, singleton Bitmap will be affected. Releases the locked context object.

MVP architecture in actual project, need to pay attention to the memory leak problem, p if long-held v layer instance, leads to v layer objects are difficult to recycle, and v is the activity or fragments as a general abstraction layer, so you need to use in p v layer of weak application or implementation in the p v layer destroy method, logic of dealing with the destruction.

The View of the drawing

The process of displaying the view in the activity interface: After the activity starts, it does not display the view immediately. Instead, it does not display the view until onResume is displayed. The WindowManager.addView method is triggered. This method fires the addView method of the proxy object WindowManagerGlobal, which creates viewRootImpl, The decorView created in setContentView is placed in The viewRootImpl setView method, and then the performTraversals method is called through the viewRootImpl setView method.

View drawing: it refers to the onMeasure, onLayout, and onDraw methods of the view. To understand these methods, we need to trace the structure of the Android interface. First, the whole is a PhoneWindow object, then a DecorView. The DecorView contains a ViewStub ToolBar, followed by a FramLayout, which is the content we usually use in our Activity setContentView. The onMeasure method is triggered in the DecorView. Its measurement rules include the width and height of the phone screen, and the measurement mode is MeasureSpec.EXACTLY. So now you know what the measure parameter of the DecorView(FrameLayout) means, and then you measure the ViewGroup below it, which has a measureChild method, Here we will ask about the measurement mode combinations of the parent layout and the child View:

ViewGroup measurement mode MeasureSpec.EXACTLY MeasureSpec.AT_MOST MeasureSpec.UNSPECIFIED
childDimension>0 size=childDimension; mode=EXACTLY size= childDimension; mode=EXACTLY size= childDimension; mode=EXACTLY
childDimension == LayoutParams.MATCH_PARENT Size = Viewgroup size; mode=EXACTLY Size = Viewgroup size; mode=AT_MOST Size = Viewgroup size; mode=UNSPECIFIED
childDimension == LayoutParams.WRAP_CONTENT Size = Viewgroup size; mode=AT_MOST Size = Viewgroup size; mode=AT_MOST Size = Viewgroup size; mode=UNSPECIFIED

After the measurement, onLayout is followed by the View’s onLayout, which is used to fix the position of the View. The method passes in several parameters relative to the position of its parent, and the upper left corner is the coordinate of (0,0). Finally, we have onDraw, which is the method we need to draw things on the canvas, generally including drawing backgrounds, drawing layers and so on.

App Startup Process

  • The split from the Linux kernel to the init process, followed by the start of a process called Zygote, andZygoteIt splits the core service process of the systemSystemServer, that is,SystemServerIt includes the bottom layerActivityManagerService,PackageManagerService,WindowManagerServiceEtc., these core services are all passedZygote.initTo start,ActivityManagerServiceBinder’s IPC communication mechanism is used to communicate with clientsActivityThreadTo establish communication.
  • When we hit Apply, the systemLauncherThe application will passstartActivityThe way to launch the application whileIntentThe acquisition of will go through the following parts:ActivityManagerServicethroughThe PackageManager resolveIntent ()Collect theintentObject pointing information. (2) The pointing information is stored in aintentIn the object. (3) The next important step is to passgrantUriPermissionLocked()Method to verify that the user has sufficient permissions to call thisintentObject directedActivity. (4) If there is permission,ActivityManagerServiceThe target is checked and launched in a new taskactivity(5) Now, it’s time to check the processProcessRecordWhether it exists.
  • So ifProcessRecordIs not null,ActivityManagerServiceA new process is created to instantiate thisactivity.
  • ActivityManagerServicecallstartProcessLocked()Method to create a new process that passes parameters to the Zygote process through the socket channel described earlier.ZygoteIncubate itself and callZygoteInit.main()Method to instantiateActivityThreadObject and eventually returns the PID of the new process.
  • The familiar ActivityThread.main method then starts the message loop with the looper. prepare and looper. loop methods
  • ContextImpl: ContextImpl: ContextImpl: ContextImpl: ContextImpl: ContextImpl: ContextImpl: ContextImpl The Application creation is handed over to the Instrumentation object, which is used to trigger subsequent activity creation and lifecycle callbacks.
  • After the Application is created, the familiar Activity is followed by the creation of the Activity to the Instrumentation object, ActivityManagerService delivers the Intent object to the Lanucher application. Lanucher’s startActivity goes through a series of actions, The result is the Instrumentation execStartActivity method, which requests ActivityManagerService and sends the information to the client through binder communicationApplicationThreadThat triggers the scheduleLaunchActivity method of the ApplicationThread, which sends a message to the Handler object of the ActivityThread and, ultimately, to the Instrumentation object to create the activity. This triggers a series of lifecycle methods.

Eventbus principle

EventBus is a publish/subscribe bus framework for Android development. Based on the observer mode, EventBus separates the receiver and sender of events. It basically consists of the following steps:

Register event subscription methods: this step is mainly to find the subscriber below what method need to be to subscribe to subscribe to operate: the method will need to be subscribed in similar HashMap stored in the data structure, convenience to send events behind and cancellation of registration when the release of resources use send events: the first step traverse the event queue, It then pulls the event out of the queue and removes it from the queue, and when it gets it, it determines what thread the event is in, and if it’s not a UI thread, it needs to be handled by a Handler, and if it is, it calls the observed method directly through reflection. Unregister: There is nothing to be said for this step, which is basically the removal of subscribed methods stored in the HashMap above, freeing resources in memory.

What are the Rxjava operators and what do they do

Just: To combine the same data sources on the observed

From: Puts a data source like an array or collection on top of the observed

Map: Transform one data source into another

Flatmap: Converts one data source to another, and the converted data is out of order

Concatmap: Converts one data source to another, and the converted data is sorted in the order of the previous data source

ToList: Converts the array form to a List collection

SubscribeOn: Sets the thread that the Observable’s call method belongs to, that is, the thread from which the data comes

ObserveOn: The thread on which the call method to subscribe is set, i.e. the data processing thread

Filter: Filters data at the observed data layer

OnErrorResumeNext: When an error occurs, you can specify the observer when the error occurs

RetryWhen: Retrace the subscribed process when errors occur

Concat: Merges objects of the same type into one object, similar to concatenating data in sets or arrays.

Zip: Handles data transmission for many different result sets, and is much more commonly used to combine multiple network requests and then process business logic uniformly. There are many more operators to look at yourself, these operators are enough for the interview.

Thread locking methods are different from class objects

Thread lock method: wait until the thread has used up the method to release the synchronization lock class object: wait until the thread has used up the synchronization lock class object: Wait until the thread has used up the synchronization lock class object

AsyncTask principle

AsyncTask encapsulates the Java thread pool in Android. By default, two thread pools are enabled in this class. One thread pool is responsible for queuing tasks to ensure that the tasks can be processed individually, and the other thread pool is dedicated to processing tasks. And then the Handler handles the thread and hands it off to the onPostExecute method.

Internal process:

  • The AsyncTask initialization phase is createdWorkerRunnableObject, which is processeddoInBackgroundThe Callable object is then createdFutureTaskObject, which will be aboveWorkerRunnableWrapped in one layerRunnableandFutureObject, which is actually the task to be performed by the thread poolWorkerRunnableObject.
  • During the execution of the task, passSerialExecutorObject to queue processingFutureTaskInside throughArrayDequeLet’s take them out in orderFutureTask, and handed it overTHREAD_POOL_EXECUTORObject, which is a thread pool created in a static code block, soTHREAD_POOL_EXECUTORIs the key to getting the job done.
  • After execution, all that remains is for the main thread’s Handler to send the message to the main thread for processing.

Question:

  • AsyncTask creates a thread pool internally?

    Two thread pools, one for queueing tasks; The other thread pool is responsible for processing FutureTask, which wraps a layer of Runnable objects around WorkerRunnable.

  • What happens if AsyncTask executes the excute method for this?

    Throw IllegalStateException directly

Talk about the characteristics of MVP and MVVM

MVP: Mainly separates M layer and V layer of code, through the P layer to establish their association, M layer and V layer decoupling. The downside is that each additional function requires additional interface callbacks. Unfortunately, the core of MVP is isolation through interfaces, leaving the relevant business layer to the P layer.

Here are a few things to note about MVP:

  • P layer logic processing a single function, do not merge a module under the increase, delete, change, check the whole function.
  • Since the P layer holds references to the V layer, weak references are usually used in the P layer to hold view layer instances, and references to the V layer need to be destroyed when the P layer is destroyed.
  • The fit class refers to that the interface classes of p layer and V layer are put into a Contract interface class. The fit class facilitates the management of the functions of the business layer, and the single functions are put into a Contract fit class. For example, we have a function to add bookshelves:
public interface AddBookShelfContract { interface View extends BaseContract.BaseView { void addBookShelfSuccess(BookShelfItem... bookShelfItem); void addBookShelfFail(); void alreadyBookShelf(BookShelfItem bookShelfItem); } interface Presenter extends BaseContract.BasePresenter<View> { void addBookShelf(String tokenId, BookShelfItem... bookShelfItem); }}Copy the code

MVVM: Mainly use the observer mode, through the change of data to inform the corresponding View change process. The M layer is the same as the M layer in the MVP, which is implemented by the network request + data cache. The double V layer is implemented by the ViewModel layer, and the V layer is implemented by the AndroidDataBinding layer. Notifies AndroidDataBinding of UI changes through observer mode. Disadvantages: AndroidDataBinding can only be worse. When writing logic in XML, there is no hint of code, feeling completely like writing JS, and readability is definitely a little hard to understand for beginners.

What is the observer mode used in Android

The observer mode is composed of a sender (sender is the author’s own name, which is much more appropriate than the observed) and an observer. When the state changes (user action, program active change, etc.), the sender actively informs all observers to refresh accordingly. The most classic android to say that the ListView data source has changed, refresh the list example. In the setAdapter, an AdapterDataSetObserver is generated, followed by the subscription to the observer, the observer onChange method inside the requestLayout method, which is the method to trigger UI changes. In BaseAdapter, you can see that notifyDataSetChanged actually triggers the notifyChanged method of the observed DataSetObservable. NotifyChanged triggers the onChange method of AdapterDataSetObserver. So you end up going to the listView requestLayout and refreshing the UI.

Talk about Google’s new Lifecycle framework

Lifecycle is managed by handing over the Lifecycle methods of a class to listen to the Lifecycle of the class so that the Lifecycle logic code is processed within Lifecycle. There are several objects involved: LifecycleObserver Interface LifecycleObserver: Classes that implement this interface can be registered with annotations through the LifecycleOwner class addObserver(LifecycleObserver o) method. LifecycleObserver can observe LifecycleOwner lifecycle events. LifecycleOwner interface (Lifecycle holder) : The class that implements this interface holds a Lifecycle object, and changes to the Lifecycle object are observed by its registered observer LifecycleObserver and trigger its corresponding events. Lifecycle = Lifecycle Unlike LifecycleOwner, which itself holds a Lifecycle object, LifecycleOwner gets an internal Lifecycle object through its Lifecycle getLifecycle() interface. State(current life cycle State) : Several event states. Event(the Event corresponding to the current Lifecycle change) : a callback Event to the state of the Event when Lifecycle changes.

Okhttp principle

Okhttp mainly implements asynchronous and synchronous network operations and creates different Call objects. The call objects here are runnable objects. Since we have many tasks, there is a Dispatcher to wrap the thread pool to handle different calls. They are used to store asynchronous tasks in progress, synchronous queues, and ready queues. Finally, in the execution of each task, the first in, first out principle of the queue is adopted to deal with each task, which is handed over to various interceptors behind, including interceptors with request preparation, cache interceptors and network connection interceptors. Each interceptor forms a responsibility chain. At the end, the response message is returned. OkHttp uses Java sockets to send and receive HTTP requests and responses. However, OkHttp implements the concept of connection pooling, which means that multiple requests from the same host can share a Socket connection. Instead of closing the underlying Socket every time an HTTP request is sent, the connection pooling concept is implemented. OkHttp encapsulates the OkIo library used for Socket reads and writes.

Retrofit principle

Retrofit is a RESTFUL web request framework based on okHttp, which uses factory mode to configure various parameters and implements web requests through dynamic proxies and annotations. Retrofit uses the factory model, Will be divided into production network request executor (callbackExecutor), network request adapterfactory (CallAdapterFactory), data converterFactory (converterFactory) and other factories. The callFactory is responsible for producing okHttp calls, and it is well known that okHttp does both synchronous and asynchronous HTTP requests by generating call objects.

The callbackExecutor generates a data callbackExecutor for each platform. The Android callback executor calls back data through a handler.

The CallAdapterFactory is a data parsing factory, usually we configure the JSON data parsing adapter.

ConverterFactory is a data conversion factory, and typically we configure Rxjava data conversion.

Retrofit implements annotations of interface class configurations through dynamic proxy patterns, parsing parameters into HTTP objects, and finally implementing network requests through okHttp.

RxJava thread switching principle

  • RxJava specifies the observer thread by subscribeOn and observeOn specifies the observer thread. IO generates IoScheduler. In the process of subscribing between the observer and the observed, the subscribeActual method of the observed will be triggered first. In this method, it can be seen that the schedule method of the Scheduler will be used eventually, so the IoScheduler mentioned above actually calls its schedule method. Will end up in NewThreadWorker generates ScheduledExecutorService object, but ScheduledExecutorService actual is founded by ScheduledThreadPoolExecutor a core thread, The maximum number of threads is integer. MAX_VALUE. Eventually by ScheduledThreadPoolExecutor submit or pass the schedule methods perform a Runnable object, the Runnable is observed the subscribe method of execution. So it explains that the observed subscribe method is executed in a child thread.

  • ObserveOn happened observer thread, AndroidSchedulers mainThread () essence is HandlerScheduler object, and in the observer, will eventually go watch part Scheduler scheduleDirect method, This method of the HandlerScheduler wraps a ScheduledRunnable object, which is processed via handler.postDelayed for the main thread.

RecyclerView source code, cache analysis

RecyclerView uses a strong division of labor operation. Display and layout are processed by LayoutManager, data display is processed by Adapter, item dynamic addition and drawing are processed by ItemDecoration, and item animation is processed by ItemAnimator. RecyclerView cache is maintained by internal Recycler. The Recycler cache has mAttachedScrap, which is used to store viewHolder cache currently displayed on the screen, and the recyclerView cache is used by mCachedViews. What is put inside is the viewHolder cache that is moved out of the screen. MRecyclerPool is the three-level cache of recyclerView, which is generally used in recyclerView nested recyclerView. For example, there is a RecyclerView item in the outer RecyclerView, then the RecyclerView inside can reduce the creation of the ViewHolder of the RecyclerView inside by sharing the RecyclerPool of the outer RecyclerView.

Binder mechanism

Binder mechanism is the cornerstone of interprocess communication on the Android side. Using AIDL’s IPC method, binder mechanism can be used to define the interface for two processes to communicate with each other. It is an inter-thread communication mechanism based on Service implementation. Its essence is C/S architecture, requires a server side, a client side. There are four objects in AIDL communication mode, one is IInterface, which is specially responsible for interface scheduling, Stub is responsible for communication response and data sent to the service end, Proxy is responsible for the communication of two processes packaging, which is indirectly called Stub packaging class. Service is the key class for the server to process data. It is represented by a graph as follows:

Android Jetpack

Android Jetpack is a set of components specially designed for developers to quickly develop app, quickly build the IMPLEMENTATION of MVVM framework, These include Lifecyle, LiveData, ViewModel, Room, DadaBinding, Navigation, Paging, WorkManager and a series of excellent frameworks.

Lifecycle: a framework that realizes the awareness of the activity and fragment Lifecycle and unties the data layer and view layer when they are destroyed. The idea is that Lifecycler adds a Fragment with no interface for each active component, implements lifecycle awareness using features that the Fragment cycle implements based on the activity’s declared cycle changes, and then executes the corresponding methods based on the annotated Event lookup.

LiveData: Provides a way to inform THE UI when data changes, and let the UI layer make corresponding logical judgment. The idea is that LifecycleOwner and Observer are stored internally. LifecycleOwner senses and handles changes in the middle of a declaration, and Observer iterates through all observers and calls back methods when data changes.

The ViewModel: It’s the bridge between our View layer and our Model layer. It’s the key point of our data-driven interface, and it’s also the key point of our UI layer. In the case of data loss, the viewModel can keep the original data. The HolderFragment holds an instance of the ViewStore, and the ViewModel is held in the ViewStore using a Map, thus retrieving the original ViewModel when the activity is recreated.

Room: is the framework of the local database in the Model layer. Through the entity mapping to the corresponding DB table structure, the entity is mapped to the DB relational database. Similar to Greendao, room database version upgrade data migration is more troublesome than Greendao migration, personally prefer Greendao to achieve local database. DadaBinding: is a framework that implements UI logic in XML layout files, and its UI layer and data layer drives both ways quite nicely.

Navigation: a new component that visually manages fragments by configuring the relationships between fragments in THE XML.

Which process does system packaging go through

  • Package resource files into R.Java class (resource index table) and. Arsc resource files through the Android Asset Packaging Tool (AAPT).
  • Process AIDL files, check if there are AIDL files in the app, if there are AIDL tools (source in System /tools/ AIDL) package into Java interface classes
  • Compile the r.java source section and aidl. Java to generate the corresponding.class file from javac.
  • Package the above.class file with a third-party JAR or library using the DX tool to generate a dex file.
  • Generate unsigned APK, including the ApKBuilder tool to package all uncompiled resources,.arSC resources, and.dex files into a completed APK file
  • Generate signed APKS, including the Jarsigner tool to verify signatures against unsigned APKs. Get a signed apK (signed.apk)
  • The zipAlign tool aligns the signed APK file.

Kotlin

Kotlin uses a new set of syntactic sugar, kotlin doesn’t let variables initialize empty types, and the powerful non-empty design idea is more user-friendly than Java and has the benefit of reminding developers at code writing stage. Its inline functions, and various shorthand ways of writing function bodies as return values, have made Kotlin more acceptable. It is favored by developers for its coordination development of better control of multi-layer nesting between threads, as well as its concise syntax.

Well, that’s about it for the Android interview. If you think there are those to make up can leave a message to me!!