tags:

views:

76

answers:

2

We have to use Asynchronous Task to start our new Activity on Tab Click event but in the ListView or any view we can directly can start the new activity Why?

+4  A: 

http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.on the UI thread.

Basically you want to avoid that the loading process/device hangs when loading loads of data to the list initially, that's why you make it async, outside the UI thread, so the user can use the app while data is loading in the background.

Starting an activity is faster than loading lots of initial data into a long list view, especially if it's remote data from a remote server. Therefore the app you're looking at is probably using this here.

Mathias Lin
it's also true when opening a sqlite database, it's better to open it and populate the list in a background thread so you haven't a 1-2 seconds frozen UI..
Rorist
+4  A: 

It is similar to option of XMLHttpRequest AJAX request in Javascript. Class Overview Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.

We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.

As shown below a new Thread is created in onClick method view source print?

1   public void onClick(View v) {
2       Thread t = new Thread(){
3       public void run(){
4     // Long running operation
5       }
6      };
7      t.start();
8   }

But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.

There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches. Handler

Let us look at the code snippet below to understand Handler approach. view source print?

01  public void onClick(View v) {
02     Thread t = new Thread(){
03    public void run(){
04         // Long time comsuming operation
05      Message myMessage=new Message();
06      Bundle resBundle = new Bundle();
07      resBundle.putString("status", "SUCCESS");
08      myMessage.obj=resBundle;
09      handler.sendMessage(myMessage);
10    }
11    };

12    t.start();
13  }

As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code. view source print?

1   private Handler handler = new Handler() {
2   @Override
3     public void handleMessage(Message msg) {
4       // Code to process the response and update UI.
5     }
6   };

After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.

Handler approach works fine, but with increasing number of long operations, Thread needs to be created, run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things. Async Task

Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.

Let us look at a sample class LongOperation, which extends the AsyncTask below: view source print?

01  private class LongOperation extends AsyncTask<String, Void, String> {
02   
03    @Override
04    protected String doInBackground(String... params) {
05      // perform long running operation operation
06      return null;
07    }
08   
09    /* (non-Javadoc)
10     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
11     */
12    @Override
13    protected void onPostExecute(String result) {
14      // execution of result of Long time consuming operation
15    }
16   
17    /* (non-Javadoc)
18     * @see android.os.AsyncTask#onPreExecute()
19     */
20    @Override
21    protected void onPreExecute() {
22    // Things to be done before execution of long running operation. For example showing ProgessDialog
23    }
24   
25    /* (non-Javadoc)
26     * @see android.os.AsyncTask#onProgressUpdate(Progress[])
27     */
28    @Override
29    protected void onProgressUpdate(Void... values) {
30        // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
31     }
32  }

Modify the onClick method as shown below: view source print? 1

    public void onClick(View v) {
2   new LongOperation().execute("");
3   }

As seen class LongOperation extends AsyncTask and implements 4 methods:

  1. doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecute: This method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.

Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

Points to remember:

  1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
  3. Task can be executed only once.
Tilsan The Fighter
@Neeraj:Hi Neeraj Refer the above the answer...
Tilsan The Fighter