跳至主要内容

使用SharedPreference实现记住密码功能

BaseActivity.kt--->


package com.example.fredric.rememberpass

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity

open class BaseActivity : AppCompatActivity() {

    var receiver: ForceOfflineReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityCollector.addActivity(this)
    }

    override fun onResume() {
        super.onResume()
        var intentFilter = IntentFilter()
        intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE")
        receiver = ForceOfflineReceiver()
        registerReceiver(receiver,intentFilter)
    }

    override fun onPause() {
        super.onPause()
        if(receiver != null) {
            unregisterReceiver(receiver)
            receiver = null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }


    inner class ForceOfflineReceiver : BroadcastReceiver() {
        override fun onReceive(context : Context?, intent0 : Intent?) {
            var builder  = AlertDialog.Builder(context!!)
            builder.setTitle("Warning")
            builder.setMessage("You are force to be offline, Please try to login again.")
            builder.setCancelable(false)
            builder.setPositiveButton("OK",{dialogInterface, which ->
                ActivityCollector.finishAll()
                var intent = Intent(context,LoginActivity::class.java)
                context.startActivity(intent)
            })
            builder.show()
        }

    }
}


LoginActivity.kt--->

package com.example.fredric.rememberpass

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Toast

class LoginActivity : BaseActivity() {

    var pref: SharedPreferences? = null
    var editor: SharedPreferences.Editor? = null
    var accountEdit: EditText? = null
    var passwordEdit: EditText? = null
    var login: Button? = null
    var rememberPass: CheckBox? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        pref = PreferenceManager.getDefaultSharedPreferences(this)
        accountEdit = findViewById<EditText>(R.id.account)
        passwordEdit = findViewById<EditText>(R.id.password)
        rememberPass = findViewById<CheckBox>(R.id.remember_pass)
        login = findViewById<Button>(R.id.login)


        var isRemember = pref?.getBoolean("remember_password",false)

        if(isRemember!!) {
            var account = pref?.getString("account","")
            var password = pref?.getString("password","")
            accountEdit?.setText(account)
            passwordEdit?.setText(password)
            rememberPass?.isChecked = true
        }


        login?.setOnClickListener({
            var account = accountEdit?.text.toString()
            var password = passwordEdit?.text.toString()

            if(account.equals("admin") && password.equals("123456")) {
                editor = pref?.edit()
                if(rememberPass?.isChecked!!) {
                    editor?.putBoolean("remember_password",true)
                    editor?.putString("account",account)
                    editor?.putString("password",password)
                }else {
                    editor?.clear()
                }

                editor?.apply()
                var intent = Intent(LoginActivity@this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }else {
                Toast.makeText(LoginActivity@this, "Account or password is invalid",Toast.LENGTH_SHORT).show()
            }
        })

    }
}



MainActivity.kt-->

package com.example.fredric.rememberpass

import android.content.Intent
import android.os.Bundle
import android.widget.Button

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val forceOffline = findViewById<Button>(R.id.force_offline)
        forceOffline.setOnClickListener({
            val intent = Intent("com.example.broadcastbestpractice.FORCE_OFFLINE")
            sendBroadcast(intent)
        })
    }
}



ActivityCollector.kt--->

package com.example.fredric.rememberpass

import android.app.Activity

class ActivityCollector {
    companion object {
        var activities = ArrayList<Activity>()

        fun addActivity(activity: Activity) {
            activities.add(activity)
        }

        fun removeActivity(activity: Activity) {
            activities.remove(activity)
        }

        fun finishAll() {
            for(activity in activities) {
                if(!activity.isFinishing) {
                    activity.finish()
                }
            }
        }
    }
}


activity_login.xml--->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="60dp">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Account:" />

        <EditText
            android:id="@+id/account"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            />
    </LinearLayout>
    
    
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="60dp">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Account:" />

        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:inputType="textPassword"
            />
    </LinearLayout>
    
    
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        
        <CheckBox
            android:id="@+id/remember_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Remember Password"/>
    </LinearLayout>
    
    
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Login"/>
</LinearLayout>


activity_main.xml--->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/force_offline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Force Offline" />
</LinearLayout>


最终效果:



评论