2015-02-11 112 views
0

我有一個活動應用程序採用抽屜菜單異步任務的片段1塊另一個異步任務不同Fragment2

public class MainActivity extends ActionBarActivity { 
.... 
void selectItem(int position) { 

      Bundle args = new Bundle(); 
      args.putInt(PageFragment.ARG_Page_NUMBER, position); 
      android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager(); 
      android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
      android.support.v4.app.Fragment fragment; 
      int ActiveFragmentId = 3; 
      if(position == 0){ 
      fragment = new Fragment1(); 
      } else if(position == 1){ 
     fragment = new Fragment2(); 
    } 
} 
.... 

和兩個片段片段1和Fragment2都在他們異步任務

現在,如果啓動Fragment1任務中的Asnc任務(即在Fragment1中的異步任務的onBackground()上保留一個斷點),並且如果我切換到Fragment2 Fragment2中的異步任務將不會工作,直到執行Fragment1的onPostExceute()。這是爲什麼?

而且getActivity()== NULL,裏面onPostExecute()Fragmnet1的異步任務,同時切換到Fragment2

回答

0

當他們在執行部分here的訂單提,執行的順序取決於你的API級別。您需要使用task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params)而不是僅僅task.execute(params)

+0

似乎現在工作(即它不是阻塞),但getActivity()== null,在Fragmnet1的異步任務onPostExecute()內,同時切換到Fragment2 – user3826273 2015-02-11 16:18:17

+0

嗯..如果你想有一個後臺任務,持續更長的時間比片段的生命週期,我會建議你使用服務。 AsyncTasks適用於短期後臺任務。 – juunas 2015-02-11 23:24:17

+0

只要活動在那裏,我就想要它,而不是碎片。所以你說切換片段在onPostExecute()內部產生'getActivity()== null',同時替換片段 – user3826273 2015-02-12 08:42:14

0

嘗試使兩個異步任務同步。