暂停方法whild asynctask运行HTTPGET

时间:2012-11-14 07:12:16

标签: java android eclipse

我有一个run()方法,其中我正在执行一个正在执行HTTPGET的Asynctask。如何使run()等待Asynctask获得结果然后继续?

2 个答案:

答案 0 :(得分:0)

//like this
    asyncRequest(URL, parameters, "POST",new RequestListener() {
                @Override
                public void onComplete(String response) { 
                    /*@todo get results and then continue */
                }

                @Override
                public void onIOException(IOException ex) {
                }

                @Override
                public void onFileNotFoundException(FileNotFoundException ex) {
                }

                @Override
                public void onMalformedURLException(MalformedURLException ex) {
                }
            }); 

public static void asyncRequest(final String requestUrl,final Bundle parameters,final String httpMethod,final RequestListener requestListener) {
        new Thread() {
            public void run() {
                try {
                    String resp = MyUtil.openUrl(requestUrl, httpMethod, parameters);
                    requestListener.onComplete(resp);
                } catch (FileNotFoundException ex) {
                    requestListener.onFileNotFoundException(ex);
                            } catch (MalformedURLException ex) {
                                requestListener.onMalformedURLException(ex);
                            } catch (IOException ex) {
                                requestListener.onIOException(ex);
                            }
            }
        }.start();
}

public static interface RequestListener {
    public void onComplete(String response);

    public void onIOException(IOException ex);

    public void onFileNotFoundException(FileNotFoundException ex);

    public void onMalformedURLException(MalformedURLException ex);
}

答案 1 :(得分:-1)

在AsyncTask的onPostExecute方法中执行run函数

    private class LongOperation extends AsyncTask<String, Integer, String> {

      @Override
      protected String doInBackground(String... params) {
            //do long asynctask activity here
      }      

      @Override
      protected void onPostExecute(String result) {
           run(); //executes the run method you want here after asysnctask is completed
      }

      @Override
      protected void onPreExecute() {
      }

      @Override
      protected void onProgressUpdate(Void... values) {
      }
}