我一直在研究Android SDK平台,有点不清楚如何保存应用程序的状态。所以,鉴于你好,Android这个小工具的改造示例: % P+ N7 o) b r5 c0 A" V; V
- K$ M% O1 D! c) s7 l6 {: U7 i+ N# C
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]我认为这对最简单的情况就足够了,但无论我如何离开应用程序,它总是会回应第一条信息。 ; ~' \' m! X3 `% u6 u) w
我相信解决方案就像覆盖一样onPause或者类似的东西一样简单,但我在文档中戳了大约30分钟,没有发现任何明显的东西。: r) v" g( h! K5 P: C* Y
: I) Z; }- V$ H* F+ r
解决方案: ; j2 [/ ^) _/ t5 R% M6 F
您需要覆盖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.} ! P1 b S L8 \- y: B9 D# R! c: x
Bundle 本质上是一种存储 NVP(“名称-值对)映射的方式将传输到onCreate()您onRestoreInstanceState()从活动中提取值的位置如下:; Q2 ^* L+ L4 O. Z
@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");} 7 n2 M$ L, t9 E( a
或者来自一个片段。 % d% {; o2 i2 o4 {. I5 s7 I& F
@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");}( L. b- x$ N+ v) L- N! m: U