若是你是一個有經驗的 Android 程序員,那麼你確定手寫過許多 onSaveInstanceState
以及 onRestoreInstanceState
方法用來保持 Activity 的狀態,由於 Activity 在變爲不可見之後,系統隨時可能把它回收用來釋放內存。重寫 Activity 中的 onSaveInstanceState
方法 是 Google 推薦的用來保持 Activity 狀態的作法。java
onSaveInstanceState
方法會提供給咱們一個 Bundle
對象用來保存咱們想保存的值,可是 Bundle
存儲是基於 key - value 這樣一個形式,因此咱們須要定義一些額外的 String
類型的 key 常量,最後咱們的項目中會充斥着這樣代碼:android
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
// ...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
複製代碼
保存完狀態以後,爲了能在系統從新實例化這個 Activity 的時候恢復先前被系統殺死前的狀態,咱們在 onCreate
方法裏把原來保存的值從新取出來:git
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
// ...
}
複製代碼
固然,恢復這個操做也能夠在 onRestoreInstanceState
這個方法實現:程序員
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
複製代碼
上面的方案固然是正確的。可是並不優雅,爲了保持變量的值,引入了兩個方法 ( onSaveInstanceState
和 onRestoreInstanceState
) 和兩個常量 ( 爲了存儲兩個變量而定義的兩個常量,僅僅爲了放到 Bundle
裏面)。github
爲了更好地解決這個問題,我寫了 SaveState 這個插件:app
在使用了 SaveState 這個插件之後,保持 Activity 的狀態的寫法以下:ide
public class MyActivity extends Activity {
@AutoRestore
int myInt;
@AutoRestore
IBinder myRpcCall;
@AutoRestore
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Your code here
}
}
複製代碼
沒錯,你只須要在須要保持的變量上標記 @AutoRestore
註解便可,無需去管那幾個煩人的 Activity 回調,也不須要定義多餘的 String
類型 key 常量。gradle
那麼,除了 Activity 之外,Fragment 能自動保持狀態嗎?答案是: Yes!ui
public class MyFragment extends Fragment {
@AutoRestore
User currentLoginUser;
@AutoRestore
List<Map<String, Object>> networkResponse;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Your code here
}
}
複製代碼
使用方法和 Activity 如出一轍!不止如此,使用場景還能夠推廣到 View
, 今後,你的自定義 View,也能夠把狀態保持這個任務交給 SaveState :google
public class MyView extends View {
@AutoRestore
String someText;
@AutoRestore
Size size;
@AutoRestore
float[] myFloatArray;
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
複製代碼
引入 SaveState 的方法也十分簡單:
首先,在項目根目錄的 build.gradle
文件中增長如下內容:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
// your other dependencies
// dependency for save-state
classpath "io.github.prototypez:save-state:${latest_version}"
}
}
複製代碼
而後,在 application 和 library 模塊的 build.gradle
文件中應用插件:
apply plugin: 'com.android.application'
// apply plugin: 'com.android.library'
apply plugin: 'save.state'
複製代碼
萬事具有!不再須要寫煩人的回調,由於你的時間很是值錢!作了一點微小的工做,若是我幫你節省下來了喝一杯咖啡的時間,但願你能夠幫我點一個 Star,謝謝 :)
SaveState Github 地址:github.com/PrototypeZ/…
Update: 最新版本已支持 Kotlin,Happy Hacking!