默認(rèn)情況下睦霎,Acticity 會自動保存數(shù)據(jù)梢卸,但在橫豎屏切換的時候,或者內(nèi)存不足被系統(tǒng)干掉的時候副女,需要手動的保存與回復(fù)一些必要的數(shù)據(jù)蛤高。
package com.psj.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val tag : String by lazy {
MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i(tag,"onCreate")
setContentView(R.layout.activity_main)
Log.i(tag,"savedInstanceState == null ? " + (savedInstanceState == null))
savedInstanceState?.getString("data")?.let {
Log.i(tag,"保存的數(shù)據(jù)為: " + it)
Toast.makeText(MainActivity@this,it,Toast.LENGTH_SHORT).show()
}
}
override fun onStop() {
super.onStop()
Log.i(tag,"onStop")
}
override fun onPause() {
super.onPause()
Log.i(tag,"onPause")
}
// 在Activity的 onStop 方法被調(diào)用之前肯定會被調(diào)用
// 如果用戶自己手動按返回按鍵導(dǎo)致銷毀Acticity,那么保存的數(shù)據(jù)無效
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Log.i(tag,"onSaveInstanceState")
//將數(shù)據(jù)保存在 outState 對象了里面
outState.putString("data", "這是我保存的數(shù)據(jù)")
}
}