仅需要在异步任务完成后运行任务

Gok*_*oku 5 java multithreading android http-post android-asynctask

如何确保异步任务在运行某些任务之前完成。我需要在异步任务更改该变量的值后使用该变量。如果我在异步运行完成之前运行代码,那么我就完蛋了。有什么帮助吗?我显然是异步任务的新手。如果您查看我的代码,我可能没有按照预期使用 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.
            }
        }
Run Code Online (Sandbox Code Playgroud)

nse*_*iuk 4

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

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

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

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

myJSONmap = JSONextractor.getJSONHMArrayL(jObject);
Run Code Online (Sandbox Code Playgroud)

在 doInBackground 上?然后打电话

locatePlace(myJSONmap);
Run Code Online (Sandbox Code Playgroud)

像这样:

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
        }


    }
}
Run Code Online (Sandbox Code Playgroud)