-5

How Can I Use Asyntask In Android I want to use it For Background Process Like Webservice Call.

Please Any One Have Idea than please tell me.

Thanks In Advance.

khushi
  • 5
  • 2
  • possible duplicate of [How to use AsyncTask correctly - Android?](http://stackoverflow.com/questions/14250989/how-to-use-asynctask-correctly-android) – Avijit Dec 24 '13 at 11:54

3 Answers3

1

Create the asynctask this way and dont forget that always do the task that relate to UI in onPreExecute() and onPostExecute() method.The task that is webservice call or db operation or whatever that you want to perform in differen thread should be in doInBackground() method.

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();
    }
}

And the create the utility class which having method for https like this:--

   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;
}
  }

And for more info about asynctask please visit the official website http://developer.android.com/reference/android/os/AsyncTask.html

Kailash Dabhi
  • 3,473
  • 1
  • 29
  • 47
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;
        }

    }
ishu
  • 1,322
  • 1
  • 11
  • 15
0

Here is good tutorial.

In short in some cases you may extend 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);
    }
  }

The <String, Void, String> in AsyncTask are:

  1. Type of parameter that passed into doInBackground.
  2. Type of value that indicates progress of the task.
  3. Type of resulted value.

In doInBackground you should execute your 'heavy' calculations. The onPostExecute executes on finish of doInBackground.

To execute your AsyncTask just call execute(url1, url2, ...)

Community
  • 1
  • 1
pbespechnyi
  • 2,251
  • 1
  • 19
  • 29