在此之后等待AsyncTask获取数据并在UI线程中执行某些操作

时间:2013-08-05 07:48:03

标签: android multithreading android-asynctask

我创建一个调用Web服务的AsyncTask实例,获取数据并将其转换为字符串。我想根据取自AsyncTask的字符串更新一些图片。 (字符串包括我要下载的一些图像URL,如果它们在我的应用程序数据文件夹中尚不存在) 我的问题是:UI线程和AsyncTask线程执行并行,我想确保结果字符串(来自AsyncTask)不为空,然后决定是否需要下载新图像。如果需要,下载照片并在我的应用程序中的某处更改布局 如何确保AsyncTask已完成任务?

请告诉您的建议或编写代码来帮助我。

这是我的代码,
活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.more_apps_layout);

    android.os.Debug.waitForDebugger();

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;

    ReceiveTask r = new ReceiveTask();
    r.execute();

    if (DataFromWebService != null)
        Log.v("sina", DataFromWebService); // !! DataFromWebService is null because AsyncTask hasn't done its task
    else
        Log.v("sing", "null");
}  

AsynTask:

class ReceiveTask extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {
        String result = null;
        JSONObject json = new JSONObject();
        try {
            json.put("command", "adv");
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);


        // ??? here coms web service!!!
        String url = "http://sina.greenbirdstudio.com/adv.php";

        try {
            HttpPost request = new HttpPost(url);
            request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
            request.setHeader("json", json.toString());
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            if (entity != null) {
                InputStream instream = null;
                instream = entity.getContent();

                //result = RestClient.convertStreamToString(instream);

                BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null)
                        sb.append(line + "\n");
                } catch (IOException e) {
                    e.printStackTrace();
                    DataFromWebService = e.toString();
                } finally {
                    try {
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        DataFromWebService = e.toString();
                    }
                }
                result = sb.toString();
            } else {
                Log.v("chize khar", " chize khar");
            }
        } catch (Exception t) {
            result = t.toString();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        DataFromWebService = result;
    }

2 个答案:

答案 0 :(得分:4)

顾名思义AsyncTask运行Asynchronous not Synchronously So put,

if (DataFromWebService != null)
        Log.v("sina", DataFromWebService); // !! DataFromWebService is null because AsyncTask hasn't done its task
    else
        Log.v("sing", "null");
}  

在AsyncTask的onPostExecute()中。

或者只使用AsyncTask的get()方法,它会等到AsyncTask完成但它会阻止UI线程。

注意:但我不建议使用.get()方法。只需在DataFromWebService onPostExecute()中使用{{1}}即可。

答案 1 :(得分:0)

onPostExecute()方法中执行您想要做的所有事情。