如何在Android中使用AsyncTask?

时间:2013-12-24 11:50:58

标签: android

如何在Android中使用Asynctask我想将它用于像Web服务调用这样的后台进程。

请任何人有想法,请告诉我。

提前致谢。

3 个答案:

答案 0 :(得分:1)

以这种方式创建 asynctask 并且不要忘记始终执行与 onPreExecute() onPostExecute()方法中的UI相关的任务。作为webservice调用或db操作的任务或者你想在差异线程中执行的任何操作都应该在doInBackground()方法中。

class CallWebservice extends AsyncTask<Double, Void, Boolean> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = ProgressDialog.show(StudentListActivity.this,
                "Calling Webservice", "Please wait...", true);
    }

    @Override
    protected Boolean doInBackground(Double... params) {
        // TODO Auto-generated method stub

        String response = null;

            response = Utillity
                    .getData(WEBSERVICE_URL);
                            return null;

    }

    @Override
    protected void onPostExecute(Boolean flag) {
        // TODO Auto-generated method stub
        super.onPostExecute(flag);
        progressDialog.dismiss();
    }
}

并创建具有https方法的实用程序类: -

   Class Utility{
public static String getData(String url) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient();
    String temp = "";

    try {

        HttpGet httpGet = new HttpGet(url.toLowerCase().replace(' ', '+'));

        HttpResponse response = httpclient.execute(httpGet);
        temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
    return temp;
}
  }

有关asynctask的更多信息,请访问官方网站http://developer.android.com/reference/android/os/AsyncTask.html

答案 1 :(得分:1)

Use This
=======
private class SetDataOfWebService extends AsyncTask<Void, Void, Boolean> {
        // ProgressDialog pDialog;
        boolean success = false;
        ConnectivityManager connectivity;

        @Override
        protected void onPreExecute() {
            // pDialog = new ProgressDialog(MailSettings.this);
            // pDialog.setMessage("Please Wait..");
            // pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (isNetworkAvailable()) {
                success = true;
                //Call WebService

            } else {
                success = false;
            }
            return success;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // if (pDialog != null && pDialog.isShowing())
            // pDialog.dismiss();
            if (result) {

            //Write Code For PostExcutive
            } else {
                return;
            }

        }

        public boolean isNetworkAvailable() {
            connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();

                if (info != null) {
                    for (int i = 0; i < info.length; i++) {
                        Log.i("Class", info[i].getState().toString());
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

    }

答案 2 :(得分:0)

这是好tutorial

简而言之,在某些情况下,您可以扩展AsyncTask:

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  }

<String, Void, String>中的AsyncTask是:

  1. 传递到doInBackground
  2. 的参数类型
  3. 指示任务进度的值类型。
  4. 结果值的类型。
  5. doInBackground中,你应该执行'重'计算。 onPostExecute完成后doInBackground执行。

    执行AsyncTask只需致电execute(url1, url2, ...)