简体   繁体   English

Android 等待异步任务完成执行特定方法

[英]Android wait till async task has finished to do specific method

I have been searching for the answer but no one really answers because there is no point using async task for that.我一直在寻找答案,但没有人真正回答,因为为此使用异步任务毫无意义。 In Android API 11 or above it will force to code it you do network requests on the main thread so I have to do async task.在 Android API 11 或更高版本中,它将强制对其进行编码,您在主线程上执行网络请求,因此我必须执行异步任务。 So, here is the question: Is it possible to wait untill the async task is finished then continue?那么,问题来了:是否可以等到异步任务完成后再继续? Because I need the data to be there for the calling method etc.因为我需要调用方法等的数据。

Here is my code:这是我的代码:

public JSONObject getJSONFromUrl(String url) {
        this.url = url;
        new loadURL().execute();



        // Do this when ASYNC HAS FINISHED 
        return jObj;



    }

    class loadURL extends AsyncTask <Void, Void, Void> {

        protected void onPreExecute() {

        }

        protected Void doInBackground(Void... unused) {
            //do stuff in background 

            return (null);
        }

    }   
}

Any questions to answer just leave a comment.有任何问题要回答,只需发表评论。 Thanks for helping.谢谢你的帮助。

yes you use the onPostExecute method of the AsyncTask to do whatever you want to do after.是的,您可以使用AsyncTaskonPostExecute方法来做您想做的任何事。 That method gets called after the doInBackground is finisheddoInBackground完成后调用该方法

If the operation won't take long (less than a few seconds) you can use the progress bar to keep from allowing the user to do anything.如果操作不会花费很长时间(少于几秒钟),您可以使用进度条来阻止用户执行任何操作。 Set something like this in your AsyncTask在你的AsyncTask设置这样的东西

ProgressDialog progress = ProgressDialog.show(LoginScreen.this, "Downloading Users", "Please wait while users are downloaded");

    @Override
    protected void onPreExecute()
    {
        progress.setCancelable(false);
        progress.isIndeterminate();
        progress.show();
    }

You will still want to call your method from onPostExecute() as this will just keep the user from being able to do anything but it won't keep any code from running that is in the method you calling the AsyncTask from您仍然希望从onPostExecute()调用您的方法,因为这只会使用户无法执行任何操作,但不会阻止运行您从中调用AsyncTask的方法中的任何代码

This can be done with wait() , notify() and notifyAll() methods of object s.这可以通过objectwait()notify()notifyAll()方法来完成。 Or You can use custom callbacks via interface s.或者您可以通过interface使用自定义回调。 Just call proper method via callback when you complete getting required data.完成获取所需数据后,只需通过回调调用适当的方法即可。

您可以在doInBackground()方法中执行网络相关操作,因为onPostExecute()方法仅用于 android 中的 UI 更新

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

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