2016-12-31 165 views
2

我可以使用AsnycTask get()方法來等待後臺任務的完成,但是如果我將CursorLoader和ContentProvider與LoaderManager回調一起使用,我該怎麼做呢?如何讓UI線程等待後臺線程完成?

是否也有可能阻止UI線程等待後臺線程中返回的數據?

+1

Loader的整個想法是,您不會讓UI線程等待,顯示空白屏幕,虛擬數據或加載微調器,直到獲取數據 – Blundell

+0

yes,其他方式如果要使用內容您需要將該過程包裝在AsyncTask中。 –

回答

0

您可以輕鬆地將您的接口獲取回調的AsyncTask。這是爲了讓您的問題

+0

AsyncTask的整體思想是提供進出主線程的一種方式。我不知道你爲什麼要使用Callback界面。 –

0

顯示ProgressDialog的解決方案,以等待,直到響應沒有收到正確的方式。如果你的回覆是從同一類別或活動接收的,則不要使用接口回呼,如果回覆是從其他類別的活動接收的,則使用接口回撥

0

等待UIThread不推薦它使應用程序看起來像laggy或stucked 。 blundell在編輯中做得很好。

0

我在我當前的項目中有一個完全相同的情況,我必須請求使用內容提供者和光標加載器的聯繫人列表,以便稍後在列表視圖中顯示它們。

因此,這裏是你應該做的:

  • 做一個異步調用內容提供商使用異步任務作爲靜態內部類whithin您的活動/片段。
  • 在AsyncTask doInBackground()方法裏面你放置你的函數來檢索光標並在那裏處理你的數據,所以你最終返回一個List<Object>對象就是我返回的模型(Contact)。
  • 裏面的AsyncTask的onPostExecute()方法,你只要傳遞retreived數據列表,無論大家認爲你正在使用(再一次在我的情況下,它是一個List<Contact>和那裏有你的mainThread正在接收數據,並只有在那裏它具有處理數據時,它已經準備好。

的AsyncTask讓你的生活變得更輕鬆,因爲他們有一個字符串結構,以處理來自MainThread將數據傳遞到後臺單獨的線程,然後從後臺線程到MainThread運回的數據。

在代碼條款應該如下所示:

public class MainActivity extends Activity { 
    private AsyncTask mTask; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // 
     ...... 
     //Call the AsyncTask and pass your Data 
     mTask = new Task(this); 
     mTask.execute(); 
    } 

    private static class Task extends AsyncTask<Void, Void, List<Object> { 
     private WeakReference<Contex> mContextRef; 
     public Task(Context context) { 
      mContextRef = new WeakReference<>(context); 
      //later when you need your context just use the 'get()' method. like : mContextRef.get() (this will return a Context Object. 
     } 

     @Override 
     protected void onPreExecute() { 
      // show progress Dialog 
      //this method is processed in the MainThread, though it can prepare data from the background thread. 
     } 

     @Override 
     protected List<Object> doInBackground(Void ... params) { 
      List<Object> mList = new ArrayList<>(); 
      //Call your content provider here and gather the cursor and process your data.. 
      //return the list of object your want to show on the MainThread. 
      return mList; 
     } 

     @Override 
     protected Void onPostExecute(List<Object> list) { 
      if(list.size() > 0) { 
      //do your stuff : i.e populate a listView 
      } 
     } 
    } 
}