总体建议是避免响应异步事件而提交事务.有关更多信息,请参见this article.但是,有时这是不可避免的,您可以设置一些更复杂的状态检查和恢复.
对于您的特定情况(似乎您希望网络请求在“活动”不再可见时立即停止),您可以采取以下措施:
public class SampleActivity extends FragmentActivity {
private static final String PROGRESS_FRAGMENT = "progress_fragment";
@Override
protected void onStart() {
super.onStart();
refreshData();
}
private void refreshData() {
if (!isInProgress) {
isInProgress = true;
showSpinner();
}
}
private void cancelRefresh() {
if (isInProgress) {
isInProgress = false;
//cancel request
hideSpinner();
}
}
private void showSpinner() {
getSupportFragmentManager()
.beginTransaction()
.add(new ProgressFragment(), PROGRESS_FRAGMENT)
.commit();
}
private void hideSpinner() {
FragmentManager mgr = getSupportFragmentManager();
Fragment spinner = mgr.findFragmentByTag(PROGRESS_FRAGMENT);
if (spinner != null) {
mgr.beginTransaction()
.remove(spinner)
.commit();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
cancelRefresh();
}
@Override
protected void onStop() {
super.onStop();
cancelRefresh();
}
}
由于您不知道将调用onSaveInstanceState(),因此可以在onSaveInstanceState()和onStop()上调用cancel.设置了标志并使用了用于跟踪片段的标记,它将仅执行一次,并且应该是安全的.