Skip to content

Instantly share code, notes, and snippets.

@douo
Last active February 27, 2016 08:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douo/7820956 to your computer and use it in GitHub Desktop.
Save douo/7820956 to your computer and use it in GitHub Desktop.
public abstract class BaseActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCommit = new LinkedList<FragmentTransaction>();
mStateSaved = false;
}
@Override
protected void onStart() {
super.onStart();
mStateSaved = false;
}
@Override
protected void onResume() {
super.onResume();
mStateSaved = false;
}
@Override
protected void onStop() {
super.onStop();
mStateSaved = true;
}
@Override
protected void onDestroy() {
mCommit.clear();
super.onDestroy();
}
protected LinkedList<FragmentTransaction> mCommit;
protected boolean mStateSaved;
protected void onResumeFragments() {
super.onResumeFragments();
while (!mCommit.isEmpty()) {
FragmentTransaction ft = mCommit.removeFirst();
ft.commit();
}
};
/**
* 模擬 FragmentManager 的行為 在 state saved 的時候暫存 Transaction 待下次恢復時再提交 當
* Transaction 發生在回調時,用這個方法提交避免發生 IllegalStateException
*
* @param ft
* @return commit 不能正確執行時返回false
*/
protected boolean commit(FragmentTransaction ft) {
try {
if (!mStateSaved) {
ft.commit();
} else {
mCommit.addLast(ft);
}
return true;
} catch (IllegalStateException ex) {
return false;
}
}
}
@spr-lfeliu
Copy link

Have you tested this?

@douo
Copy link
Author

douo commented Mar 14, 2014

@luisfeiliurp yes, This code already run in some products which have million user totally, It help me avoid illegalStateException when activity go to background but not fix when activity destroyed.

@lapngodoan
Copy link

Hi Douo,
Do you have any solution when activity destroyed?

@hongyangAndroid
Copy link

thx a lot . But I have some confusion on it .

"1. we discard all fragment transaction after activity has been destroyed" , based on this , I have a question , If onSaveInstanceState method be called by the framework , is it possible the Activity is still alive ?

  • if impossible , I think the codes on BaseActivity may can't make sense , because the activity will be recreate when restore .
  • if possible , can you give me some example ?

Is there something I misunderstand ? hope for you answer :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment