AACHulk


AACHulk is based on Google’s ViewModel+LiveData framework,

Combining Okhttp + Retrofit + BaseRecyclerViewAdapterHelper + SmartRefreshLayout + ARouter to build a fast development framework, development language is Kotlin, Then combine AACHulkTemplate template development for development, avoid some tedious operations, provide development efficiency,AACHulkTemplate development update waiting

Function is introduced

1. Supports configuration of server addresses, MOCK server addresses, success codes, various timeout periods, and interceptors

2. Support to customize a variety of abnormal View replacement

3. Retry when interface invocation errors occur

4. Support Activity and Fragment display to meet business requirements

5. Support for multiple layout adapters

6. Support multi-service reuse of ViewModel

7. Support common code generation of AACHulkTemplate template

Third-party libraries

  1. OkhttpAn HTTP client for Android, Kotlin, and Java
  2. RetrofitSecure HTTP client for Android and Java
  3. BaseRecyclerViewAdapterHelperPowerful and flexible universal adapter
  4. SmartRefreshLayoutAndroid smart drop-down refresh framework
  5. ARouterA routing framework to help componentize Android Apps

Basis function

1. Add dependencies

Join at build. Grade in project

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
        google()
        jcenter()
    }
}
Copy the code

Add to build.grade in the main project app

API 'com. Madreain: libhulk: 1.0.4'Copy the code

2. Inherit HulkApplication and configure related configuration items

LibConfig.builder() .setBaseUrl(BuildConfig.BASE_URL)//baseurl .setMockUrl(BuildConfig.MOCK_URL)//mockurl .setretSuccess (1).addokHttpInterceptor (RequestHeaderInterceptor() .addokHttpInterceptor (MockInterceptor())// Address configuration of the mockURL .addretcodeInterceptors (SessionInterceptor());Copy the code

For details about how to configure the preceding configuration items, see Demo

You can also configure a uniform style according to the relevant SmartRefreshLayout document, set it individually, or customize it according to your project

3. Inherit BaseResponseBean to encapsulate unified data acceptance according to its own project

5. Write ApiService and put interfaces

6. Write generic tools. XML in libhulk for app use because the Kotlin-Android-Extensions plugin may be limited to its own module resource files. Therefore, you can only write generic tools.xml in your APP project

⚠️ if the big guys have a good implementation method welcome advice

️🔥️🔥 port port AACHulkTemplate. This template must be used to ensure that ApiService and tool. XML have been created and can be modified by users according to their own projects

Rapid development of

The AACHulkTemplate template is nice to use, so let’s go through the manual steps, using SingleActivity as an example

1. Create a BaseActivity inheritance from SingleActivity

class SingleActivity : BaseActivity(R.layout.activity_single) { private val singleViewModel by viewModels<SingleViewModel>() override fun init(savedInstanceState: Bundle?) {/ / ActionBar associated Settings ActionBarUtils. SetSupportActionBarWithBack (the toolbar, null, The View. An OnClickListener {onBackPressed ()}) ActionBarUtils. SetToolBarTitleText (the toolbar, "single data display interface")}}Copy the code

2. ARoute configuration

Determine whether to configure ARoute for routing control based on project requirements

@Route(path = RouteUrls.Single)
Copy the code

3. Create an object

@Keep
data class SingleData(
    var code: String,
    var name: String
)
Copy the code

4. Create SingleViewModel and inherit ViewModel

class SingleViewModel : ViewModel() {


    fun cityList(page: IPage, onSuccess: (data: List<SingleData>?) -> Unit) {
        NetHelper.request(page, block = {
            NetHelper.getService(ApiService::class.java).getCityList().asResult()
        }, onSuccess = {
            onSuccess(it)
        }, onError = {
            ToastUtils.showLong(it.message)
        })
    }

}

Copy the code

5. Call the interface and process data

CityList (this, onSuccess = {it? .let { tv.text = it[0].name } })Copy the code

At this point, a simple interface call to the data presentation is done

⚠️⚠️⚠️ For the demo with an adapter, see ListActivity

Use the advanced

1. Customize various abnormal state View replacement

Rewrite buildPageInit method, create IPageInit, you can rewrite the implementation of IPageInit method, to create your app for the default interface, exception error interface

Encapsulated with pull-down refresh and load more ListViews support setEmpty Settings for different empty interface displays

2. The interceptor

2.1 Request header interceptor

class RequestHeaderInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { return chain.proceed(processRequest(chain.request())) } private fun processRequest(request: Request): Request {if (Request == null) return Request val newBuilder = request.newBuilder() // Set the relevant headers return newBuilder.headers(addHeaders()).build() } fun addHeaders(): Headers { return Headers.Builder() .add("app_id", "wpkxpsejggapivjf") .add("app_secret", "R3FzaHhSSXh4L2tqRzcxWFBmKzBvZz09") .build() } }Copy the code

2.2 MOCK Interceptors

Practical application: Can be used to MOCK the interface early in the App

@EverythingIsNonNull class MockInterceptor : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { var request = chain.request() val originalUrl = request.url.toString() val path = originalUrl.substring(LibConfig.getBaseUrl().length) return if (sMockUrls.contains(path)) { request = request.newBuilder().url("${LibConfig.getMockUrl()}$path") .build() chain.proceed(request) } else { Proceed (request)}} companion object {private val sMockUrls = listOf("")}}Copy the code

2.3 Abnormal state response code interceptor

Practical application: it can be applied to the unified processing of fixed code in App, such as mutual kick operation and seal number

class SessionInterceptor : ErrorInterceptor(-100) { override fun interceptor(throwable: Throwable): Boolean { // TODO: Return true}}Copy the code

3. Message bus

In response to your questions, LiveEventBus(disadvantage: it does not support thread distribution) is used to replace the original EventBus. The switch setting of setEventBusOpen in HulkConfig is removed, and you can choose your own message bus according to your project

LiveEventBusMessage bus, based on LiveData, with life cycle awareness, support Sticky, support AndroidX, support cross-process, support cross-app

Refer to the official documentation for specific implementation methods

4. The use of Lottie

The powerful animation library Lottie is used for refreshing headers and loading styles, so that cool and suitable animations can be designed for THE UI according to the APP

The relevant data

🌟🌟🌟 recommends Kotlin by Carson_Ho: this is a comprehensive & detailed grammar study guide for class use

Thank you

Thanks to the authors of all the tripartite libraries used in this framework, as well as all the developers and organizations who make selfless contributions to open source, so that we can work and learn better, I will also give back to the open source community in my spare time

About me

License

Licensed under the Apache License, Version 2.0 (the "License") Copyright [2020] [Madreain] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.Copy the code