How does Android simply implement a function of judging login before jumping to the page?

(It requires clicking a button to trigger a login judgment before jumping to a certain activity, and automatically jumping to the target activity after a successful login)

Here, BaseApplication is used for data transfer, and the code block object is used as the data storage for jump execution code:

class BaseApplication : Application() {
    
    
    companion object {
    
    
        @JvmStatic
        var isLogin: Boolean = false
        @JvmStatic
        var loginSuccessCall: () -> Unit = {
    
    }
    }
}

There are three activities here: MainActivity, LoginActivity, StackShowActivity (you need to log in before entering), and now you need to jump from MainActivity to StackShowActivity. (All Activities inherit from BaseActivity)

open class BaseActivity : AppCompatActivity() {
    private val TAG = "BaseActivity"
    /**
     * 核心逻辑
     */
    fun goActivityWhenLogin(detail: () -> Unit) {
        when (isLogin()) {
            true -> detail.invoke()
            false -> goLoginAct(detail)
        }
    }

    private fun goLoginAct(detail: () -> Unit) {
        BaseApplication.loginSuccessCall = detail
        startActivity(Intent(this, LoginActivity::class.java))
    }

    /**
     * 登录成功后调用
     */
    fun loginSuccess() {
        BaseApplication.loginSuccessCall.invoke()
    }

    private fun isLogin(): Boolean {
        return BaseApplication.isLogin
    }
}

Click to jump in MainActivity:

fun toStackShowActivity(view: View) {
    goActivityWhenLogin {
        val intent = Intent(this, StackShowActivity::class.java)
        intent.putExtra("url","http://**")
        startActivity(intent)
    }
}

Called after successful login in LoginActivity:

fun setLoginSuccess(view: View) {
    BaseApplication.isLogin = true
    finish()
    loginSuccess()
}

The above functional requirements can be achieved.
The overall idea is two points:

  1. Code block object for data storage
  2. BaseApplication for data transfer

The code here is just for example. In the actual program design, you also need to consider whether loginSuccessCall has been consumed (not everyone will first use a custom jump method like goActivityWhenLogin).

After reading the article, if it is helpful, don't forget to like or like it!

Guess you like

Origin blog.csdn.net/ganshenml/article/details/120519423