作法有蠻多種,其中一種請參考 Android AsyncTasks during a screen rotation, Part I

簡單來說是在 onSaveInstanceState() 裡面把 資料&狀態 存起來,然後在 onRestoreInstanceState() 再把它 restore 回來,並繼續執行 AsyncTask。這裡順便簡介一下:

onSaveInstanceState() 會在activity被銷毀之前執行,
而 onSaveInstanceState() 儲存的bundle資料,會在onCreate()或是onRestoreInstanceState()時載入。
--- Android開發筆記-UI狀態儲存

以下附上程式碼

@Override
protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        final AddTask task = mAddTask;
        if (task != null && task.getStatus() != UserTask.Status.FINISHED) {
            final String bookId = task.getBookId();
            task.cancel(true);

            if (bookId != null) {
                outState.putBoolean(STATE_ADD_IN_PROGRESS, true);
                outState.putString(STATE_ADD_BOOK, bookId);
            }

            mAddTask = null;
        }
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.getBoolean(STATE_ADD_IN_PROGRESS)) {
            final String id = savedInstanceState.getString(STATE_ADD_BOOK);
            if (!BooksManager.bookExists(getContentResolver(), id)) {
                mAddTask = (AddTask) new AddTask().execute(id);
            }
        }

最後一種作法(不是很被大家推薦!),請見 How to handle an AsyncTask during Screen Rotation?
是在 AndroidManifest.xml ,把現在這個 activity 多加一個 attribute

android:configChanges="keyboardHidden|orientation"

然後再在 activity 裡面的 onConfigurationChanged() 中再做設定。

Comments

comments powered by Disqus
Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project