androidkotlinandroid-studiologout

How to automatically log a user out of their account and force them to log back in? (Kotlin Android)


LoginPref.kt:

package com.example.sepehr1.Session

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.example.sepehr1.MainActivity

class LoginPref {
    lateinit var pref:SharedPreferences
    lateinit var editor:SharedPreferences.Editor
    lateinit var con: Context
    var PRIVATEMODE : Int = 0

    constructor(con: Context){
        this.con = con
        pref = con.getSharedPreferences(PREF_NAME, PRIVATEMODE)
        editor = pref.edit()
    }

    companion object{
        val PREF_NAME = "Login_Preference"
        val IS_LOGIN = "isLoggedin"
        val KEY_PHONE = "phonenumber"
        val KEY_PASSWORD = "password"
    }

    fun createLoginSession(phoneNumber: String, password: String){
        editor.putBoolean(IS_LOGIN, true)
        editor.putString(KEY_PHONE, phoneNumber)
        editor.putString(KEY_PASSWORD, password)
        editor.commit()
    }

    fun checkLogin(){
        if(!this.isLoggedIn()){
            var i : Intent = Intent(con, MainActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            con.startActivity(i)
        }
    }

    fun getUserDetails(): HashMap<String, String>{
        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_PHONE, pref.getString(KEY_PHONE, null)!!)
        (user as HashMap).put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null)!!)
        return user
    }

    fun LogoutUser(){
        editor.clear()
        editor.commit()
        var i = Intent(con, MainActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        con.startActivity(i)
    }

    fun isLoggedIn(): Boolean{
        return pref.getBoolean(IS_LOGIN, false)
    }
}

MainActivity.kt (Login Page) :

class MainActivity : AppCompatActivity() {

lateinit var session: LoginPref


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    session = LoginPref(this)
    var username = findViewById<EditText>(R.id.phoneNumber)
    var password = findViewById<EditText>(R.id.passwords)

    if(session.isLoggedIn()){
        var i : Intent = Intent(applicationContext, dashboard::class.java)
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(i)
        finish()
    }
    signIn.setOnClickListener {
        var phone = username.text.toString().trim()
        var pass = password.text.toString().trim()

        if(phone.isEmpty() && pass.isEmpty()){
            Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
        } else{

            session.createLoginSession(phone, pass)
            var i : Intent = Intent(applicationContext, dashboard::class.java)
            startActivity(i)
            finish()
        }
}

And "dashboard" is the Layout showed to the user who has successfully signed In

The problem is that when the user successfully enters the application for the first time, he always enters the main page (dashboard) without entering the login page. I want, for example, the user to re-enter the application with login page after 10 days (that is, every 10 days the program will automatically log him out and force him to re-enter with the login page)

How can I do that according my code?


Solution

  • You can achieve what you want by simply using a Periodic WorkManager that does the log-out in the background even if the app is not running. Follow these steps:

    class LogOutWorkManager(val context: Context,
       val workerParameters: WorkerParameters) : Worker(context, workerParameters){
    
        override fun doWork(): Result {
            val loginPref = LoginPref(context)
    
            return try {
                loginPref.LogoutUser()
                Result.success()
            }catch (e: Exception){
                Result.retry()
            }
    
        }
    
    }
    
    

    A few suggestions before I continue.

    val request = PeriodicWorkRequestBuilder<LogOutWorkManager
                      >(10, TimeUnit.DAYS)
                  .setInitialDelay(10, TimeUnit.DAYS)
                   .build()
               WorkManager.getInstance(context)
                   .enqueue(request)
    

    Make sure you configure your work request properly. Also, you can reduce the initialDelay time to say 15 minutes(supported minimum time) to test the implementation.

    You can read more about WorkManager here.