在我的應用程序中,我總是需要在應用程序第一次打開時執行一些操作。當用戶打開它時,應用程序將顯示一個帶有進度條的對話框,同時在後臺執行AsyncTask
,之後(在onPostExecute()
上)我需要提交Fragment
。在調用onDestroy之後處理AsyncTask.onPostExecute中的FragmentTransaction的最佳方法
所以,在我的主要Activity
的onCreate()
方法,我有:
public class InitialActivity extends SherlockFragmentActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
if(savedInstanceState == null) //Executes just at the firstTime
{
//ApplicationStarter -> It manages all execution to start my app, executes asynctask, shows dialogs..
ApplicationStarter starter = new ApplicationStarter(this) {
@Override
public void afterFinish() {
//It Executes at onPostExecute when doInBackground() finishes
ItensFragment itensfrag = new ItensFragment();
frag.setTargetFragment(itensfrag , 0);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.simple_fragment, itensfrag);
ft.commitAllowingStateLoss();
}
};
starter.start();
}
}
}
所以,一切正常的話,但應用程序崩潰,如果用戶旋轉設備或之後onDestroy()
方法被調用。以下異常啓動:
java.lang.IllegalStateException: Activity has been destroyed
在ft.commitAllowingStateLoss();
我搜索周圍,我發現on this post,這是不是裏面的異步回調方法執行Fragment
transiction像我試圖做一個很好的做法。 And i saw this answer也可以,我可以適應我的情況。但在此之前,我想知道是否有人有更好的方法或建議我想要做什麼。
在此先感謝。
發生在方向改變你的活動被破壞並重新創建bcoz。 Asynctask顧名思義是異步的 – Raghunandan
如果有幫助,你可以查看這個博客。 http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html – Raghunandan