简体   繁体   English

AsyncTask类的正确方式如何等待另一个AsyncTask类完成其过程

[英]How is the correct way of an AsyncTask class wait for another AsyncTask class to finish its processes

I'm doing an app that access a Web Service and with the JSON I get from it I create an object and use it in my code. 我正在做一个访问Web服务的应用程序,并使用从中获取的JSON创建一个对象并将其用于代码中。 Even though my app is working I don't know it is well written and flawless. 即使我的应用程序正常运行,我也不知道它编写得很好且完美无缺。

I'll explain what I have then put some Sample codes to demonstrate... First of all I created an Activity with a EditText and a Button, where the user will type a code and click in the button to access my database and check if it exists. 我将解释一下,然后放入一些示例代码进行演示...首先,我创建了一个带有EditText和Button的Activity,用户将在其中键入代码并单击该按钮以访问我的数据库并检查是否它存在。 The main is here: In my button.OnClickListener I check if the EditText has something on it and if I have internet connection <- (I've never had any problem on this) and after that I call my class RestClient that is extended from AsyncTask, that access the WebService in background and get a object from it. 主要是在这里:在我的button.OnClickListener中,我检查EditText上是否有东西,以及是否有Internet连接<-(我从没遇到任何问题),然后我调用了从AsyncTask,它在后台访问WebService并从中获取一个对象。 And only after this I will get the result from this RestClient. 而且只有之后,我才能从此RestClient获得结果。 My solution was to start a new AsyncTask that waits my RestClient and then start the process to get the object. 我的解决方案是启动一个新的AsyncTask,等待我的RestClient,然后启动获取对象的过程。

here is the sample of my code my restClient that Return an Generic Object from my webservice: 这是我的restClient的代码示例,该代码从Web服务返回通用对象:

public class RestClient<t>  extends AsyncTask<String, String, String> {

private Class<t> tClass;
private t ObjReturn;

public RestClient(Class<t> tClass)
{
    this.tClass = tClass; 
}

public Object getObjectResponse(){
    return ObjetoDeRetorno;
}

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

@Override
protected String doInBackground(String... OnlyTheURL) {
    String urlString = OnlyTheURL[0];
    String error = null;
    WebApiDeRetorno = new WebApiRetorno();
    try {
        Log.i("RestClient","Starting connection");

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.connect();

        String result = convertStreamToString(connection.getInputStream());

        connection.disconnect();

        JSONObject jsonObject = new JSONObject(result);

        String obj = jsonObject.get("returnObject").toString();

        Gson gson = new Gson();
        ObjReturn = gson.fromJson(obj, tClass);


    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return error;
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    }
}

my buttom function: 我的臀部功能:

buttonConfirmar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            restClient = new RestClient<>(MyObject.class);

            restClient.execute(getString(R.string.WebServiceURL));
            new WhenWebServiceConnectionFinished().execute();

        }
    });

The other AsyncTask Class that is executed AFTER RestClient and needs to Wait it finish: 在RestClient之后执行并需要等待其完成的另一个AsyncTask类:

private class WhenWebServiceConnectionFinished extends AsyncTask<String, Void, Boolean> {
    @Override
    protected void onPreExecute() {
        progressDialog.show();
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {

        //THIS IS WHAT I DON'T KNOW IF IT'S OK TO DO:
        do {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (restClient.getStatus() != AsyncTask.Status.FINISHED);
        //WAITING THE restClient.getStatus CHANGE TO FINISHED WITH Thread.sleepS.

        if (checkWebApiRetorno()) {
            objectReturnFromWebApi = (MyObject) restClient.getObjectResponse();

            Intent intent = new Intent(thisActivity, NewActivity.class);
            startActivity(intent);
            finish();
            return true;
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        if (progressDialog.isShowing())
            progressDialog.dismiss();

        if (!success)
            dialogBuilder.create().show();

        super.onPostExecute(success);
    }
}

Add callback to first AsyncTask and run second only after onPostExecute fired by first AsyncTask 将回调添加到第一个AsyncTask并仅在第一个AsyncTask触发onPostExecute之后运行第二个回调

Something like 就像是

public interface AsyncFinishedCallback{
    public void onAsyncFinished();
}

and in first AsyncTask do constructor like this 并在第一个AsyncTask做这样的构造函数

public RestClient(Class<t> tClass, AsyncFinishedCallback callback)
{
    this.tClass = tClass; 
    this.callback = callback; //declare it somewhere as a field
}

and than 然后

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if(callback!=null)
        callback.onAsyncFinished();
    }
}

Than in button function 比按钮功能

buttonConfirmar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {


        restClient = new RestClient<>(MyObject.class, new AsyncFinishedCallback(){
    @Override
    public void onAsyncFinished(){
            new WhenWebServiceConnectionFinished().execute();
    }
});

        restClient.execute(getString(R.string.WebServiceURL));

try this: start another task when u get result from first Async task use AsyncTask<String, String, Boolean> 尝试以下操作:当您从第一个Async task获取结果时启动另一个任务,请使用AsyncTask<String, String, Boolean>

    public class RestClient<t>  extends AsyncTask<String, String, Boolean> {

private Class<t> tClass;
private t ObjReturn;

public RestClient(Class<t> tClass)
{
    this.tClass = tClass; 
}

public Object getObjectResponse(){
    return ObjetoDeRetorno;
}

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

@Override
protected Boolean doInBackground(String... OnlyTheURL) {
    String urlString = OnlyTheURL[0];
    String error = null;
    WebApiDeRetorno = new WebApiRetorno();
    try {
        Log.i("RestClient","Starting connection");

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.connect();

        String result = convertStreamToString(connection.getInputStream());

        connection.disconnect();

        JSONObject jsonObject = new JSONObject(result);

        String obj = jsonObject.get("returnObject").toString();

        Gson gson = new Gson();
        ObjReturn = gson.fromJson(obj, tClass);
        return true;

    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return  false;;
    }
  return true;
}

@Override
protected void onPostExecute(Boolean result) {
    if (result) {
            //success occurs task finish
             new WhenWebServiceConnectionFinished().execute();
         } else {
                //error occurs 
            }
        }
    }
}

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

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