java 只有在异步任务完成后才需要运行任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12964997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:59:39  来源:igfitidea点击:

need to run tasks only after Async task has finished

javaandroidmultithreadingandroid-asynctaskhttp-post

提问by Goku

How do i make sure that the async tasks finishes before i run certain tasks. I need to use a variable AFTER the async tasks changes the value of that variable. If i run the code before async is done running then im screwed. any help? im obviously new to async tasks. If you look at my code im probably not using onPostExecute() as it was intended so advice would be helpful. My initial thought was to keep adding things to the async task but im thinking that this is just bad practice since i have tons of things that must be run in series. Basically, what i think it boils down to is: how do i make sure that the tasks in the UI thread dont start to run before my async task has finished.

在运行某些任务之前,我如何确保异步任务完成。我需要在异步任务更改该变量的值后使用变量。如果我在异步完成之前运行代码,那么我就搞砸了。有什么帮助吗?我显然是异步任务的新手。如果您查看我的代码,我可能没有按预期使用 onPostExecute(),因此建议会有所帮助。我最初的想法是继续向异步任务添加内容,但我认为这只是不好的做法,因为我有大量的东西必须连续运行。基本上,我认为它归结为:如何确保在异步任务完成之前 UI 线程中的任务不会开始运行。

public class MainActivity extends MapActivity {
myJSONmap;

public void onCreate(Bundle savedInstanceState) {
new AsyncStuff().execute();
locatePlace(myJSONmap);

 class AsyncStuff extends AsyncTask<Void, Integer, JSONObject> {
            @Override
            protected JSONObject doInBackground(Void... params) {
                jObject = GooglePlacesStuff.getTheJSON(formatedURL);
                return null;
            }
            @Override
            protected void onPostExecute(JSONObject result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                myJSONmap = JSONextractor.getJSONHMArrayL(jObject);  // getting the parsed data from the JSON object.
                //the arraylist contains a hashmap of all the relevant data from the google website.
            }
        }

采纳答案by nsemeniuk

You probably want to read more about AsyncTask on Android Developer

您可能想在 Android Developer 上阅读有关 AsyncTask 的更多信息

http://developer.android.com/intl/es/reference/android/os/AsyncTask.html

http://developer.android.com/intl/es/reference/android/os/AsyncTask.html

About tips, my personal choice is to pass a Boolean to onPostExecute. That way you can evaluate if the doInBackground was succesful, an then figure out what to do (Error message or update the layout).

关于提示,我个人的选择是将布尔值传递给 onPostExecute。这样您就可以评估 doInBackground 是否成功,然后找出要做什么(错误消息或更新布局)。

Keep in mind that in onPostExecute method ideally should onlymake the screen update, assuming you have the data ok. In your example, why not include the

请记住,在 onPostExecute 方法中,理想情况下应该更新屏幕,假设您的数据正常。在您的示例中,为什么不包括

myJSONmap = JSONextractor.getJSONHMArrayL(jObject);

on the doInBackground? And then call

在 doInBackground 上?然后打电话

locatePlace(myJSONmap);

Like this:

像这样:

class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
    String errorMsg;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... v) {
        try{
            jObject = GooglePlacesStuff.getTheJSON(formatedURL);
            myJSONmap = JSONextractor.getJSONHMArrayL(jObject);
            //do stuff
            return true;
        } catch (JSONException e){
            errorMsg="Something wrong in the json";
            return false;
        }

    }

    @Override
    protected void onPostExecute(Boolean success) {
        if(success){
            locatePlace(myJSONmap);
            //update layout
        } else {
            //show error
        }


    }
}

回答by Pankaj Kushwaha

You can ue below code to execute async task -

您可以使用下面的代码来执行异步任务 -

MyAsyncTask_a asyncTask_a = new MyAsyncTask_a();
                        asyncTask_a.execute();

Once doInBackground() task is finished then only control will go to postExecute(). You can't perform any UI operations in doInBackground , but you can do so in preExecute() and postExecute().

一旦 doInBackground() 任务完成,那么只有控制权将转到 postExecute()。您无法在 doInBackground 中执行任何 UI 操作,但您可以在 preExecute() 和 postExecute() 中执行此操作。

class MyAsyncTask_a extends AsyncTask<Void, Void, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);


        }
    }

Hope this will help you.

希望这会帮助你。