活动被销毁或暂停时如何恢复?

时间:2011-06-21 01:02:51

标签: android savestate

好的,所以我很难保存我的活动状态,这样当活动被销毁时,它可以恢复用户上次停止的位置。这是我的源代码。如果有人能看到它并告诉我如何保存和恢复是非常感谢。

这是我的代码......

                public class DorothyTalk extends Activity{
    Handler handler = new Handler();
    int typeBar;
TextView text1;
EditText edit;
Button respond;
private String name;
private ProgressDialog progDialog;
@Override 
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dorothydialog);

    text1 = (TextView)findViewById(com.fttech.da.R.id.dialog);
    edit = (EditText)findViewById(com.fttech.da.R.id.repsond);
    respond = (Button)findViewById(com.fttech.da.R.id.button01);

    Talk();

}

    protected Dialog onCreateDialog(int id) {
switch(id) {
case 0:                      // Spinner
    progDialog = new ProgressDialog(this);
    progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progDialog.setMessage("Loading...");
    progDialog.setProgress(100);

    return progDialog;

}     return progDialog; }         public void Talk(){

    text1.setText("Welcome what is your name?");

    respond.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            name = edit.getText().toString();
            new AsyncTask<Void, Integer, Void>(){

            @Override
        protected Void doInBackground(Void... arg0) {
            try {                 
             Thread.sleep(1000);             
            } catch (InterruptedException e) {                         
                e.printStackTrace();             
                    }            
                    return null;
            }
            @Override         
        protected void onPostExecute(Void result) {             
                    text1.setText("Nice to meet you "+name);
                    dismissDialog(typeBar);
                     }


                @Override        
        protected void onPreExecute() { 
            typeBar = 0;
        showDialog(typeBar);

        }

        }.execute((Void)null);

        }
    });
    }


    public void onBackPressed()
      {
        int i = Log.d("CDA", "onBackPressed Called");
        Context localContext = getApplicationContext();
        Intent localIntent = new Intent(localContext, mainMenu.class);
        startActivityForResult(localIntent, 0);

        return;




    }

如何在销毁活动时保存和恢复?

2 个答案:

答案 0 :(得分:0)

您必须在销毁活动之前保存数据。您可以使用isFinishing()

测试是否要销毁它

protected void onPause(){ 如果(isFinishing()){  保存数据(); } }

然后你需要重新加载你的数据onCreate()

答案 1 :(得分:0)

您可以尝试覆盖

public Object onRetainNonConfigurationInstance() {

    //object returned here can always be recovered in getLaststNonConfigurationInstance()
    return something;
}

并使用getLastNonConfigurationInstance()来恢复状态。