如何正确使用AsyncTask?

时间:2017-07-12 22:12:52

标签: android android-asynctask

我有一个JSONobject var(名为Acumulator),其中我积累了一些Json节点。当时间过去后,我需要通过http发送此JSONObject Accumulator的内容。为此,我需要使用AsyncTask。

我是这样做的:

private class doSynchLocationsTask extends AsyncTask<JSONObject, Void, Boolean> {

    @Override
    protected Boolean doInBackground(JSONObject... params) {
      //do the job
      if (OK) return true
      else return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
      if (!result) { 
        // here my problem how to access the JSONObject to put it back
        // in the original Acumulator to process it again later ?
      }      
    }

}

JSONObject tmpAccumulator = mAccumulator;
mAccumulator = new JSONObject();  
new doSynchLocationsTask().execute(tmpAccumulator);  
但是我不确定我做得好。首先不确定当我用tcccumulator交换tmpAccumulator时,这段代码是否有内存泄漏或类似的东西,然后我不知道如何在onPostExecute中访问JSONObject(即:tmpAccumulator)把它放回mAccumulator让系统稍后再处理它们

2 个答案:

答案 0 :(得分:1)

为您的自定义AsyncTask类创建构造函数。在创建AsyncTask类的新对象时,将变量作为参数发送。

private class CustomAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private String myString;

    public CustomAsyncTask(String myString) {
        this.myString = myString;
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        //use myString whereever you want in Custom AsyncTask class
        return null;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        //use myString whereever you want in Custom AsyncTask class
    }
}

这样称呼:

String myString = "test";

    new CustomAsyncTask(myString).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

答案 1 :(得分:1)

无需为AsyncTask创建构造函数。

试试这样的事情:

private class doSynchLocationsTask extends AsyncTask<JSONObject, Void, Boolean> {
    private JSONObject mJsonObject;

    @Override
    protected Boolean doInBackground(JSONObject... params) {
      mJsonObject = params[0];
      //do the job
      if (OK) return true
      else return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
      if (!result) { 
        // here my problem how to access the JSONObject to put it back
        // in the original Acumulator to process it again later ?

        // Reference mJsonObject here
      }      
    }
}