Simple and easy-to-use SPI framework on Android, full version open download

Posted by jplush76 on Fri, 18 Feb 2022 01:33:40 +0100

Preface

In my recent articles about preparing for an Android interview, I found that Framework is a very important point that many large companies value.

As shown in the picture, this is a conversation within one of our technical exchange groups_

In the Android technology article I wrote a while ago, I read thousands of articles about Framework, but many friends believe privately that I said the article was not detailed enough, the article was not deep enough, and I couldn't learn anything.

I feel a passion for this knowledge point, and I have been paying attention to this knowledge recently.

Not long ago, a friend of Tencent said that there was a T4 geek who stayed up late every day until the morning, had liver for half a month, and refined the Android Framework kernel resolution into a 452-page PDF! What's more - now this material is open for download!

Unexpectedly, someone just sent me a pillow when I wanted to sleep. When I learned the internal information, I switched on the computer and rapped on the keyboard to tell you the news:

Here comes the dry goods you want!!!

1. Overview of MVVM architecture patterns

This is the MVVM architecture mode + Kotlin protocol + JetPack(ViewModel+LiveData)+Retrofit architecture to implement a small DEMO for the WanAndroid login interface, which will gradually improve the WanAndroid client in the future

1,ViewModel

In order to separate View view View data ownership from the interface controller Activity/Fragment logic, the architecture component provides the interface controller with a ViewModel helper class, which is responsible for preparing data for the interface. ViewModel objects are automatically retained during configuration changes so that the data they store is immediately available for the next Activity or Fragment instance.

2,LiveData

LiveData is an observable data storage class with life cycle awareness, meaning that it follows the life cycle of other application components such as Activity, Fragment, or Service to ensure that LiveData only updates application component observers in an active life cycle. LiveData objects are usually stored in ViewModel objects and can be accessed through the getter method.

3. Kotlin Protocol

Collaborations are dependent on threads, enabling sequential writing of asynchronous code and automatic thread switching. And the ViewModelScope defines the ViewModelScope for each ViewModel in the application. If the ViewModel has been cleared, the protocols started within this scope will be automatically cancelled.

4,Retrofit

Declare the network request function in the service interface as a suspend suspend interface function to support Kotlin threads and transfer the suspend function result as a LiveData object.

2,ViewModel

//Get ViewModel
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)` 

The time range within which the ViewModel object exists is the Lifecycle passed to the ViewModelProvider when the ViewModel is acquired. ViewModel will remain in memory until Lifecycle, which limits its time range, disappears permanently: for Activity, when Activity completes; For Fragments, it is when Fragments are separated.

3,LiveData

//Observing User data
viewModel.user.observe(this, Observer {
    //Show login results
    if (it.errorCode == 0) {
        Toast.makeText(this, it.data?.nickname, Toast.LENGTH_SHORT).show()
    } else {
        Toast.makeText(this, it.errorMsg, Toast.LENGTH_SHORT).show()
    }
})

Using LiveData has the following advantages: Ensure that the interface conforms to the state of the data

LiveData Follow the observer pattern. When the life cycle state changes, LiveData Will notify Observer Object. You can incorporate code to do this Observer Update interface in object. Instead of updating the interface every time changes are made to the applied data, the observer can update the interface every time a change occurs.

No memory leaks

Observers are bound to Lifecycle Objects are cleaned up after their associated life cycle is destroyed.

No crash caused by Activity stopping

If the life cycle of the observer is inactive (such as returning to the stack) Activity),Then it will not receive any LiveData Event.
There is no longer a need to manually process life cycles
 Interface components simply observe the relevant data and do not stop or resume the observation. LiveData All these operations are automatically managed because they can be observed with awareness of related life cycle state changes.

Data is always up to date

If the life cycle becomes inactive, it receives the latest data when it becomes active again. For example, once in the background Activity Receives the latest data immediately after returning to the foreground.

Appropriate configuration changes

If recreated due to configuration changes such as device rotation Activity or Fragment,It immediately receives the latest available data.

shared resource

Can be extended using single instance mode LiveData Objects encapsulate system services to share them in applications.

4. Kotlin Protocol

4.1. The nature of asynchronism

What is asynchronous?

Asynchronous is the simultaneous execution of more than one task for different purposes.

But what about asynchronous for tasks that have back-and-forth dependencies?

Processing using callback mechanisms in asynchronization.

Why do I need an asynchronous callback mechanism?

Because there are before and after dependencies between different tasks.

What are the drawbacks of the asynchronous callback mechanism?

Code structure is over-coupled, encountering nested coupling of multiple function callbacks, called callback hell, which makes code difficult to maintain.

What is the solution to callback to Hell?

Chain call structure.
The common way is to use RxJava,It is reactive function programming in Java Implementation in.
however RxJava The creation, transformation and consumption of midstream require a variety of classes and rich operators. RxJava The cost of learning.
Reduce use without packaging RxJava,Because you can't guarantee that everyone on your team will understand it and make the right choices when making changes.

In serial execution, although the code is executed sequentially, it is actually executed sequentially on different threads. So why use callbacks when the code execution sequence is consistent in serial execution?

Because execution is blocked during serial execution, blocking the main thread can cause serious problems, so all time-consuming operations cannot be performed in the main thread, so multi-threaded parallel execution is required.

In parallel execution, an asynchronous callback is actually a multithreaded sequential execution of code. Is it possible to write code sequentially and have the code execute in a different thread order, automatically completing the switching of threads?

That's it Kotlin Protocol.
Kotlin A protocol is an implementation of a stackless protocol, whose control flow depends on the state flow of the state machine generated by the compilation of the body itself, and variable preservation is also achieved through the closure syntax.

Conclusion:

Asynchronous callbacks are multithreaded sequential execution of code, and Kotlin Collaborations enable sequential writing of asynchronous code and automatic thread switching.

So what is the principle of automatic thread switching for a collaboration?

Yield: Yield CPU,Give up scheduling control and go back to the last time Resume Places
Resume: Get scheduling control, continue executing the program until the last time Yield Places

Example:

1. GlobalScope.launch A protocol was launched and IO Executed on a thread,
2\. In a collaboration, call the interface to get the result.
3. Get results, use withContext(Dispatchers.Main)Switch to main thread and update interface

4.2. Type of protocol

Is the scope of a protocol, which refers to the period of time during which code within a protocol runs. If it exceeds the scope of a specified protocol, the protocol will be cancelled.

GlobalScope

Refers to the same scope of the process as the application process, in which code within the process can run before the process has ended.

Lifecycle-aware scope of collaboration provided in JetPack:

ViewModelScope,For each of the applications ViewModel Definition ViewModelScope. If ViewModel If cleared, the processes started in this scope will be cancelled automatically.

LifecycleScope,For each Lifecycle Object Definition LifecycleScope. Protocols started within this scope will Lifecycle Cancel when destroyed.

Use LiveData You may need to calculate the value asynchronously. have access to liveData Builder Function Call suspend Function and use the result as LiveData Object transfer.

Related links: https://developer.android.google.cn/topic/libraries/architecture/coroutines

4.3. Startup of protocol

launch method:

/**
 * Important knowledge: ViewModel + protocol
 */
fun ViewModel.launch(
    block: suspend CoroutineScope.() -> Unit,
    onError: (e: Throwable) -> Unit = {},
    onComplete: () -> Unit = {}
) {
    viewModelScope.launch(CoroutineExceptionHandler { _, e -> onError(e) }) {
        try {
            block.invoke(this)
        } finally {
            onComplete()
        }
    }
}

Source code:

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

4.3.1, launch method explanation

context

In the context of a collaboration, you can specify the thread on which the collaboration runs. Default vs. specified CoroutineScope In coroutineContext Be consistent, for example GlobalScope Run in a background worker thread by default. You can also change the threads running the collaboration by displaying the specified parameters. Dispatchers Several values are provided to specify: Dispatchers.Default,Dispatchers.Main,Dispatchers.IO,Dispatchers.Unconfined. 

start

Start mode of the protocol. Default CoroutineStart.DEFAULT It means that the program is executed immediately, in addition to CoroutineStart.LAZY,CoroutineStart.ATOMIC,CoroutineStart.UNDISPATCHED. 

block

The main body of the collaboration. That is, code that runs within a collaboration can be passed through lamda Expressions are a convenient way to write code that runs in a coprocess.

CoroutineExceptionHandler

Appoint CoroutineExceptionHandler To handle exceptions within the protocol.

Job

Returns a value that references the currently created protocol. By Job Of start,cancel,join And other methods to control the start and cancel of the protocol.

4.4, suspend pending function

The suspend keyword only serves to flag that this function is a time-consuming operation that must be executed in a collaboration, while the withContext method does the switching of threads.

Code in a consortium automatically switches to other threads and then back to the main thread! Sequential writing guarantees logical intuition, and automatic thread switching of the process guarantees non-blocking of the code. Suspended functions must be called in the coprocess or other suspended functions, that is, the suspended functions must be executed directly or indirectly in the coprocess.

So why isn't the code in the collaboration executed in the main thread? And why does it automatically cut back to the main thread after execution?

A suspension of a process can be understood as the process in which code in the process leaves the thread in the process, and the recovery of the process can be understood as the process in which code in the process re-enters the thread in the process. A collaboration is a switching of threads through this suspended recovery mechanism.

4.5. async await method

The suspend method is wrapped in the async method to execute concurrent requests, and once the concurrent results are all returned, switch to the main thread, then use the await method to get the concurrent request results.

5,Retrofit

HTTP interface suspend suspend function:

interface ApiService {
    @FormUrlEncoded
    @POST("user/login")
    suspend fun loginForm(@Field("username")  username: String,@Field("password")  password: String): BaseResponse<User>
}

kotlin generic:

data class BaseResponse<T>(
    val errorCode: Int=0,
    val errorMsg:String? = null,
    var data: T? = null
)

This is the MVVM architecture mode + Kotlin protocol + JetPack(ViewModel+LiveData)+Retrofit architecture to implement a small DEMO for the WanAndroid login interface, which will gradually improve the WanAndroid client in the future

summary

This is the end of the writing. Put a small benefit at the end of the article. Here is a learning idea and direction about Flutter sorted out by Xiaobian himself in the process of learning, engaged in Internet development. The most important thing is to learn technology well. Learning technology is a slow and hard road, which can not be learned by passion for a moment or by a few days and nights. We must cultivate the habit of hard work in peacetime, and more importantly, we need accurate learning direction to achieve effective learning results.
Since there is only a general outline for more content, more detailed study of mind mapping is required. Click on my Tencent document to get it for free.
Free advanced UI, performance optimization, architect courses, NDK, ReactNative+Weex Wechat applets, Flutter's comprehensive Android advanced practice technical data, and technical bulls to discuss and communicate solutions.

One of the learning ideas and directions sorted out in the course of Flutter, engaged in Internet development, the most important thing is to learn good technology, and learning technology is a slow and hard road, which can not be learned by momentary passion or by enduring a few days and nights. We must develop the habits of hard work in peacetime, and more accurately study direction is needed to achieve effective learning results.
Since there is only a general outline for more content, more detailed study of mind mapping is required. Click on my Tencent document to get it for free.
Free advanced UI, performance optimization, architect courses, NDK, ReactNative+Weex Wechat applets, Flutter's full range of advanced Android hands-on technical information, and technical bulls to discuss and communicate solutions. **

Topics: Android Programmer