简体   繁体   English

如何让UI线程等待后台线程完成?

[英]how to allow UI thread to wait for the background thread to finish?

I can use AsnycTask get() method to wait for the background task to be completed, But how do I do it if I'm using CursorLoader and ContentProvider with LoaderManager Callback? 我可以使用AsnycTask get()方法等待后台任务完成,但是如果我将CursorLoader和ContentProvider与LoaderManager Callback一起使用怎么办?

Is it also possible to prevent the UI thread from waiting for the data returned in the background thread? 是否还可以防止UI线程等待后台线程返回的数据?

您可以轻松地通过您的界面来获取Asynctask的回调。这是解决问题的正确方法

Show ProgressDialog to wait untill response is not receive. 显示ProgressDialog等待直到没有收到响应。 if your response is receiving from same class or activity then do not use interface call back, if response is receiving from other activity of class then use interface call back 如果您的响应是从同一类或活动接收的,则不要使用接口回调;如果响应是从类的其他活动接收的,则使用接口回调

Wait on UIThread is not recommended it makes app looks like laggy or stucked. 不建议等待UIThread,它会使应用看起来很滞后或卡住。 blundell made good point in the edit. blundell在编辑中指出了重点。

I have exactly the same situation in one of my current project where i have to request the list of contacts using the content provider and cursor loaders to display them later on a listview. 在我当前的项目之一中,我遇到的情况完全相同,在该项目中,我必须使用内容提供程序和游标加载程序请求联系人列表,以便稍后在列表视图中显示它们。

So here is what you should do: 所以这是你应该做的:

  • Make an Async call to the content provider from whithin your activity/fragment using the async task as a static inner class. 使用异步任务作为静态内部类,从您的活动/片段中向内容提供者进行异步调用。
  • Inside the AsyncTask doInBackground() method you place your function to retrieve the cursor and process your data there so you end up with returning a List<Object> Object is the returned Model (Contact) in my case. 在AsyncTask doInBackground()方法内部,您可以放置​​函数来检索游标并在那里处理数据,因此最终返回List<Object>对象。在本例中,对象是返回的Model(联系)。
  • Inside the AsyncTask's onPostExecute() method you just pass the retreived data list to whatever View you are working with (again in my case it's a List<Contact> and there where your mainThread is receiving data and only there it has to process the data when it's ready. 在AsyncTask的onPostExecute()方法中,您只需将检索到的数据列表传递给您正在使用的任何View(同样,在我的情况下,它是List<Contact> ,在那里mainThread接收数据,并且只有在处理数据时,准备好了。

AsyncTask make your life much easier as they have a string structure to handle passing data from a MainThread to a background separate Thread and then ship back the data from the background Thread to the MainThread. AsyncTask使您的工作变得更加轻松,因为它们具有字符串结构来处理将数据从MainThread传递到后台单独的Thread,然后将数据从后台Thread传递回MainThread。

In terms of code your code should look like : 在代码方面,您的代码应类似于:

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
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM