Android AsyncTask HttpClient with Notification example - Notification using Notification.Builder method

In this tutorial we will learn how to make HTTP post using AsyncTask, basically running the process in a separate thread than the UI thread so it doesn't interfere with user actions while processing a time and resource consuming task. At the same time with the help of Notification Manager we can get timely alerts regarding our background process. An asynchronous task runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

The three types used by an asynchronous task are the following:


  • Params, the type of the parameters sent to the task upon execution.
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation

When an asynchronous task is executed, the task goes through 4 steps:


  • onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  • doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  • onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  • onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task


A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Notification(int icon, CharSequence tickerText, long when)

This constructor is deprecated. Use Notification.Builder instead. 
The Notification.Builder has been added to make it easier to construct Notifications.
package com.as400samplecode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class MyAsyncTask extends AsyncTask<String, Void, String> {

    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    private final HttpClient httpclient = new DefaultHttpClient();

    final HttpParams params = httpclient.getParams();
    HttpResponse response;
    private String content =  null;
    private boolean error = false;

    private Context mContext;
    private int NOTIFICATION_ID = 1;
    private Notification mNotification;
    private NotificationManager mNotificationManager;

    public MyAsyncTask(Context context){

        this.mContext = context;

        //Get the notification manager
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    }

    protected void onPreExecute() {
        createNotification("Data download is in progress","");
    }

    protected String doInBackground(String... urls) {

        String URL = null;
        String param1 = "abc";
        String param2 = "xyz";

        try {

            //URL passed to the AsyncTask 
            URL = urls[0];
            HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
            ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);


            HttpPost httpPost = new HttpPost(URL);

            //Any other parameters you would like to set
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("param1",param1));
            nameValuePairs.add(new BasicNameValuePair("param2",param2));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

            //Response from the Http Request
            response = httpclient.execute(httpPost);

            StatusLine statusLine = response.getStatusLine();
            //Check the Http Request for success
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
            }
            else{
                //Closes the connection.
                Log.w("HTTP1:",statusLine.getReasonPhrase());
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }


        } catch (ClientProtocolException e) {
            Log.w("HTTP2:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        } catch (IOException e) {
            Log.w("HTTP3:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        }catch (Exception e) {
            Log.w("HTTP4:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        }

        return content;
    }

    protected void onCancelled() {
        createNotification("Error occured during data download",content);
    }

    protected void onPostExecute(String content) {
        if (error) {
            createNotification("Data download ended abnormally!",content);
        } else {
            createNotification("Data download is complete!","");
        }
    }

    private void createNotification(String contentTitle, String contentText) {

        //Build the notification using Notification.Builder
        Notification.Builder builder = new Notification.Builder(mContext)
        .setSmallIcon(android.R.drawable.stat_sys_download)
        .setAutoCancel(true)
        .setContentTitle(contentTitle)
        .setContentText(contentText);

        //Get current notification
        mNotification = builder.getNotification();

        //Show the notification
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}

How to call AsyncTask from your Android Activity

String url = "http://www.mysamplecode.com/DowloadData";
new MyAsyncTask(this).execute(url);

6 comments :

  1. Where to add

    String url = "http://www.mysamplecode.com/DowloadData";
    new MyAsyncTask(this).execute(url);

    two lines into Coding?

    Thanks in advance

    ReplyDelete
    Replies
    1. Probably as onClick handler.

      Delete
  2. hello, how do I get what the method returns "protected String doInBackground(String... urls)" in android ativity?? thanks

    ReplyDelete
  3. there is content returned from the function this is gonna be your answer and data u need. parse it whatever u want.

    ReplyDelete
    Replies
    1. Please Illustrate with a short example to use the content of MyAsyncTask into code.

      Thanks in Advance.

      Delete
  4. I used it like this

    String url = "http://alok.6te.net/droidAjax.php";

    String op = example(url);

    public String example(String url){


    String output = null;
    try {
    output = new MyAsyncTask(this).execute(url).get();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    return output;
    }


    If I use HttpPost in in MyAsyncTask than it gives error in logcat saying
    HTTP method POST is not supported by this URL

    so I changed it to following

    try {

    //URL passed to the AsyncTask
    URL = urls[0];
    HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
    ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);


    HttpGet httpGet = new HttpGet(URL);
    //HttpPost httpPost = new HttpPost(URL);

    //Any other parameters you would like to set
    List nameValuePairs = new ArrayList(2);
    nameValuePairs.add(new BasicNameValuePair("param1",param1));
    nameValuePairs.add(new BasicNameValuePair("param2",param2));
    //httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //Response from the Http Request
    response = httpclient.execute(httpGet);

    ReplyDelete