Android uses Startup and Lifecycle to create a separate test module

Preface
Sometimes we will inevitably write some test codes in the project (such as environment switching, test pages, etc.), these codes may exist in different places, it is inconvenient to manage and modify, and there is no need to enter these codes when going online production package. So can we write these test codes in a non-intrusive way? Component-based development, we can create a separate module to store these test codes. The following methods are used when the app module depends on the test module
debugImplementation project(':module_test').
Among them, the test module depends on the base, and there are tool classes for managing activities in the base.
Here comes the question, how does this test module monitor the startup of the app and perform some initialization?
insert image description here
Method 1
First of all, it is definitely possible to use EventBus or broadcast. We can send a notification when the app starts.
Method 2
We can also let the test module expose an interface or method, and call this method initially when the application starts.
Method 3
You can also use the StartUp component of Jetpack.

The App Startup library provides a simple and efficient way to initialize components when the application starts.

The practice of using StartUp is as follows:
Create the following classes in the test module:

class TestInitializer : Initializer<Unit> {

    override fun create(context: Context) {//这里拿到context是Application
        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationObserver()) //可以结合Lifecycle监听应用生命周期以获取activity信息
    }

    override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf()

}

Then the manifest file of the test module

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cbim.test">

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application>

        <activity android:name=".TestActivity"/>

        <provider
            android:name="androidx.startup.InitializationProvider"
            android:authorities="${applicationId}.androidx-startup"
            android:exported="false"
            tools:node="merge">
            <meta-data
                android:name="com.cbim.test.TestInitializer"
                android:value="androidx.startup" />
        </provider>
    </application>

</manifest>

It can be combined with Lifecycle to monitor the application life cycle to obtain the activity information on the top of the stack, because the activity has not been created and added during the create() of the Initializer. Here, activity is used for permission checking and permission application.

package com.cbim.test

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.alibaba.android.arouter.launcher.ARouter
import com.cbim.guangxi.building.utils.AppManager
import com.cbim.lib_common.router.RouteConstants
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.interfaces.OnPermissionResult
import com.lzf.easyfloat.permission.PermissionUtils

/**
 * @Desc:
 * @Author:  leiertao
 * @Date:  2022/8/26
 */
class ApplicationObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        if (PermissionUtils.checkPermission(AppManager.currentActivity())) {
            showFloat()
        } else {
            Toast.makeText(AppManager.currentActivity(),
                "请开启悬浮窗权限,方便测试使用",
                Toast.LENGTH_SHORT).show()
            Handler(Looper.getMainLooper()).postDelayed({
                PermissionUtils.requestPermission(AppManager.currentActivity(),
                    object : OnPermissionResult {
                        override fun permissionResult(isOpen: Boolean) {
                          // if (isOpen)  showFloat()
                        }
                    })
            }, 3000)

        }

    }

    private fun showFloat() {
        EasyFloat.with(AppManager.currentActivity())
            .setLayout(R.layout.float_layout)
            .setShowPattern(ShowPattern.FOREGROUND)
            .setDragEnable(true)
            .registerCallback {
                createResult { _, _, view ->
                    view?.setOnClickListener {
                        ARouter.getInstance().build(RouteConstants.TEST_ACTIVITY).navigation()
                    }
                }
            }
            .show()
    }
}

I opened a floating button in ApplicationObserver. Note that opening the floating window requires <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
the final effect as shown below.

insert image description here
In this way, we can use the floating button to test related functions like using vconsole

Guess you like

Origin blog.csdn.net/qq_36162336/article/details/126587113