Use Kotlin+MVP+AndroidX to build Android project framework

Recently, I have studied kotlin in depth, and found that it is quite good, especially the coroutine, which has changed my habit of using threads for Android development in the past. This thing is convenient to use, and it saves all kinds of callbacks and The trouble of communication between the main and sub-threads, of course, if you are used to Java, the cost is still quite high if you want to switch to kotlin and use coroutines to transform your project. Google is gradually replacing Java with kotlin, and is also replacing the android support package with androidx, and MVP is also a very popular design pattern (and MVVM) in the past two years. In order to keep up with the trend, this tutorial will take you to build a kotlin-based +MVP+AndroidX's basic framework of Android projects can also let novices understand the process of building a project. If you are starting a new project or planning to refactor a project, I hope this tutorial can give you some reference value.

Before that, you need to have a certain understanding of the following knowledge:

1. Kotlin (especially coroutines, Baidu can find a lot of documents, so I won’t go into details here)

2. MVP design pattern (refer to my other blog: Android MVP design pattern )

In fact, MVVM is more convenient to use coroutines. Kotlin provides good support for the architecture component ViewModel, but there are already many examples of MVVM on the Internet. I will write about the use of MVP here.

Don't ask why you don't use RxJava, you just don't like it (if you add coroutines, the transformation cost is a bit high and not elegant enough).

development tools:

Android Studio 3.2+ (I use AS3.5)

1. Create a project

Create a project, choose kotlin as the basic language (AS will automatically configure kotlin for you, and AS3.5 uses AndroidX by default), and since it is clear to use the MVP design pattern, I design the project structure as follows:

The specification can refer to: Android Development Specification

2. Migration of AndroidX

Google officially said that the SDK 28.0.0 version is still used, android.support,but subsequent versions will use androidx, so although we may not have any impact in the near future, in order to adapt to changes in future versions, it is definitely a good thing to start gradually connecting to androidx now. good thing. But at present, many third-party libraries still use the support version, which brings some trouble to the migration. For the complete mapping relationship between support and androidx, please refer to: official documents

1. If you already have a project, AndroidStudio3.2 and above provide a one-click migration function, as shown below:

2. Before migrating, make sure that the gradle version of your project must be 3.2.0+, and the compileSdkVersion must be 28 or higher

classpath 'com.android.tools.build:gradle:3.5.2'

3. Add configuration in the gradle.properties file:

android.useAndroidX=true
android.enableJetifier=true
  • android.useAndroidX: If set to  true, the Android plugin will use the corresponding AndroidX library instead of the support library. If not specified, the flag defaults to  false.
  • android.enableJetifier: If set to  true, the Android plugin rewrites its binaries, automatically migrating existing third-party libraries to use AndroidX. If not specified, the flag defaults to  false.

4. Remove the support.appcompat dependency from the old project and add the following dependency:

implementation "androidx.appcompat:appcompat:1.0.2"

At this point, the migration is complete

important point:

1. The control of the support package is referenced in the layout file, and the package name needs to be manually changed to androidx

2. Introduce a third-party library to see if it supports androidx, and directly introduce its new version if it supports it

3. Migration of kotlin

Refer to my other blog: AndroidStudio configures kotlin

Note that the version of the kotlin plugin also has requirements for the version of gradle, pay attention to the corresponding relationship.

//kotlin依赖
implementation "androidx.core:core-ktx:+"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.60"
//使用协程
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"

4. Project configuration

(1) Specify the third-party libraries that need to be used. This project uses the following third-party libraries. Common popular frameworks such as butterknife, Glide, etc. are added according to individual needs. This is just a sample project. It is worth noting that these popular frameworks are large Some have started to support androidx, which is a good thing.

//OkHttp
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
//今日头条屏幕适配方案
implementation 'me.jessyan:autosize:1.1.2'
//权限申请
implementation 'me.weyye.hipermission:library:1.0.7'

(2) Fill in the basic permissions required for the project (increase as needed in actual development)

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.INTERNET"/>

(3) For the adaptation configuration of each Android version, refer to: Android Version Adaptation Tour

(4) Configuration of obfuscation rules, reference: Android code obfuscation (continuously improved in actual development)

5. Create a base class

In the project, some base classes are generally created to encapsulate some common operations

6. Packaging tools

Create some commonly used tool classes under the utils package, and encapsulate some common tool methods

7. MVP

MVP involves Model, View, Presenter

Model: Used to store some network, database, file read and write operations, etc., to obtain data sources

View: corresponds to Activity, Fragment, Adapter, etc., only does UI operations, and does not do time-consuming operations such as network requests.

Presenter: Execute the method provided by the Model, get the data, and then pass it to the View for binding display

For details, see the project source code

Such a simple project framework is basically built. This project is just a demonstration project without much business logic. Individuals can be flexible according to the actual situation.

Postscript: About kotlin coroutines

1. Coroutine scope

GlobalScope: Equivalent to global scope, not associated with specific Activity or Fragment life cycle, abuse will cause memory waste

MainScope: It is understood as the scope of local use, which can be associated with the life cycle of Activity and so on

ViewModelScope: Exclusive to the MVVM architecture, projects that use ViewModel can use this directly

Custom scope:

 private val viewModelJob = SupervisorJob()
 private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob) //UI作用域
uiScope.launch {//主线程(UI线程)
         val deferred = async(Dispatchers.IO){//异步线程(IO线程)
                delay(2000)
                "result"
         }
         showToast(defferred.await())//UI操作
     }
 }

2. Cancel the coroutine

After the coroutine is created, pay attention to calling cancel() to cancel when the Activity life cycle ends.

viewModelJob.cancel()

The above is the architecture based on the MVP pattern. Next, I will teach you step by step how to transform it into the MVVM pattern and introduce architectural components such as Lifecycle, LiveData, and ViewModel. Stay tuned

Guess you like

Origin blog.csdn.net/gs12software/article/details/103261053