我一直在研究Android SDK平台,有点不清楚如何保存应用程序的状态。所以,鉴于你好,Android这个小工具的改造示例:% {1 w# {3 U" j) h/ _6 k
j1 w2 p' U( Q$ z% i# E. X
package com.android.hello;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity { private TextView mTextView = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); mTextView = new TextView(this); if (savedInstanceState == null) mTextView.setText("Welcome to HelloAndroid!"); else mTextView.setText("Welcome back."); setContentView(mTextView); }code]我认为这对最简单的情况就足够了,但无论我如何离开应用程序,它总是会回应第一条信息。 ( z- D! v) `& d
我相信解决方案就像覆盖一样onPause或者类似的东西一样简单,但我在文档中戳了大约30分钟,没有发现任何明显的东西。: d- `* x' ~! z
9 B9 U: \4 l% r% b+ g" e* V& C3 Y2 ?
解决方案: % S2 D$ ]7 x' J T# S
您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要改变的应用程序状态值写入Bundle参数如下:[code]@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean",true); savedInstanceState.putDouble("myDouble",1.9); savedInstanceState.putInt("MyInt",1); savedInstanceState.putString("MyString","Welcome back to Android"); // etc.} : o8 J# A% a5 [! r u6 c7 w
@Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");}# }; i) H) M, m4 g
或者来自一个片段。 % n4 `0 g" X) G, Y0 G% y# u, W
@Overridepublic void onViewStateRestored(@Nullable Bundle savedInstanceState) super.onViewStateRestored(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");} 6 @. S3 v; ^$ J, ~