2010년 12월 30일 목요일

[Android Course][English][Theme] - AsyncTask




Thread normal use, the following have been using a lot.
First, Subclassing the Thread class to define a new object that fired Thread: run () method to override.
Second, the new operator to create a new Thread object as an argument and creates the Runnable interface (including logic executed on the thread) is the way forward.

If these methods complicated and Logic, management seems to be harder.
So I was looking the other way was found during a New Class.
That "AsyncTask" Class is.



AsyncTask (Asynchronous Task) - [Overview]

: Background working in all aspects of Android (thread object creation, use, UI thread and communication, etc.), especially in the Activity code is included in the background thread is the UI widgets and more frequent communication, more and more hungry Activity Code because of the complexity, the problem To solve the API level 3 (1.5 version) that provides a class called from the AsyncTask.

: AsyncTask class every day for a background task (thread creation, job execution, UI and communications, etc.) are abstractions.
And each of the 'background' task implementation and management of objects in units that aims to be convenient.

AsyncTask (Asynchronous Task) - Usage











: AsyncTask look at the inheritance relationship,
AsyncTask a Generic Class that inherits from Object, because you must specify the type you want to use. AsyncTask class must be specified when using the generic type is used for each of the following.
     - Params: doInBackground () data type of the specified
     - Progress: onProgressUpdate () data type for the specified
     - Result: onPostExecute () data type of the specified

- AsyncTask Class Base.
private class receiveRollback extends AsyncTask<Object, Object, Object> {

  // UI Thread AsynchTask CallBack is executed by the first
  protected void onPreExecute() {
  }

  // UI Thread AsynchTask actual work done by the CallBack
  protected String doInBackground(Object... params) {
    return result;
  }

  // OnInBackground CallBack for displaying the progress of work
  protected void onProgressUpdate(Object... progress) {
  }

  // Once onInBackground CallBack automatically runs
  protected void onPostExecute(Object result) {
  }

  // Cancel this operation is executed when onInBackground CallBack
  protected void onCanelled(){
  }
}



※ 주의 사항
1) AsyncTask class should always be used by subclassing.

2) AsyncTask instance is always created on the UI thread.
3) AsyncTask: execute (...) method is always invoked in UI thread.

4) AsyncTask: execute (...) method generated by AsyncTask instance can be used just once. Another such instance execute (...) When you run the exception occurs, which AsyncTask: cancel (...) method has been canceled by the work done before the same is true if AsyncTask instance. So the background work needed for the task using the new operator creates a new instance should AsyncTask.

5) The callback function ncTask onPreExecute (), doInBackground (...), onProgressUpdate (...), onPostExecute (...) should not be called directly. (I only use callback)

[Example Test Code]
1. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 <ProgressBar
  android:id="@+id/progressbar"
  style="?android:attr/progressBarStyleHorizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:paddingBottom="20px" />

 <TextView 
  android:id="@+id/result"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Result"
     android:paddingBottom="20px" />
    
    <Button
     android:id="@+id/executetask"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="AsyncTask Start" />
   
</LinearLayout>

2. main.java
package com.Example_AsyncTask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class main extends Activity {
 ProgressBar m_progressBar = null;
 TextView m_Result = null;
 Button m_ExecuteTask = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        m_progressBar = (ProgressBar)findViewById(R.id.progressbar);
        m_Result = (TextView)findViewById(R.id.result);
        m_ExecuteTask = (Button)findViewById(R.id.executetask);
       
        m_ExecuteTask.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    new ExampleAsyncTask().execute("1","2","3","4","5","6");
   }
       
        });
    }
   
   
    private class ExampleAsyncTask extends AsyncTask<String, Integer, Long> {     
     // UI Thread AsynchTask CallBack is executed by the first
     @Override
  protected void onPreExecute() {
      m_Result.setText("Background Thread Start");
   super.onPreExecute();
  }
     // UI Thread AsynchTask actual work done by the CallBack
  @Override
     protected Long doInBackground(String... strData) {
   long result = 0;
      int numberOfParams = strData.length;
   
      for(int i=0; i<numberOfParams; i++) {   
       SystemClock.sleep(1000);
       // onProgressUpdate callback
       publishProgress((int)(((i+1)/(float)numberOfParams)*100));
      }   
      return result;
     }
   
  // OnInBackground CallBack for displaying the progress of work
     @Override
     protected void onProgressUpdate(Integer... progress) {
      m_progressBar.setProgress(progress[0]);
     }
   
     //  Once onInBackground CallBack automatically runs
     @Override
     protected void onPostExecute(Long result) {
      m_Result.setText("Background Thread End");
     }
   
     //Cancel this operation is executed when onInBackground CallBack
     @Override
  protected void onCancelled() {
   // TODO Auto-generated method stub
   super.onCancelled();
  }   
    }
}


=> Example Source Code: If you need, please contact us.

댓글 없음:

댓글 쓰기