zoukankan      html  css  js  c++  java
  • AsyncTask

    AsyncTask也叫做“异步任务”,是一个抽象类
       AsyncTask约定了在子线程中运行任务的抽象方法,开发人员能够在自己定义AsyncTask的实现类中重写该方法,
       则AsyncTask在工作时会自己主动开启子线程运行相关代码
    AsyncTask类的声明:
       public abstract class AsyncTask<Param,Progress,Result>
            Param 运行异步任务后,须要參数的数据类型
                     Progress 运行异步任务过程中。标识进度的数据类型
    Result 运行异步任务后。须要返回的结果的数据类型


    AsyncTask中的抽象方法: public abstract Result doInBackground(params... params)
    让AsyncTask開始工作:
        public final AsyncTask<params,Progress,Result> execute(params...params)
        该方法被调用后。会自己主动开启子线程并调用dnInBackground()方法,该方法
        必须在UI线程中调用
                案例:

        布局:

    1. <Button  
    2.        android:id="@+id/button1"  
    3.        android:layout_width="wrap_content"  
    4.        android:layout_height="wrap_content"  
    5.        android:layout_alignParentTop="true"  
    6.        android:layout_centerHorizontal="true"  
    7.        android:layout_marginTop="104dp"  
    8.        android:onClick="doAsyncTask"  
    9.        android:text="開始" />  

    MainActivity:

    1.  public class MainActivity extends Activity {  
    2.   
    3.     @Override  
    4.     protected void onCreate(Bundle savedInstanceState) {  
    5.         super.onCreate(savedInstanceState);  
    6.         setContentView(R.layout.activity_main);  
    7.         System.out.println("onCreate" + Thread.currentThread().getId());  
    8.     }  
    9.       
    10.     public void doAsyncTask(View view){  
    11.         new InnerAsyncTask().execute("");  
    12.     }  
    13.     private class InnerAsyncTask extends AsyncTask<Object, Object, Object>{  
    14.   
    15.         @Override  
    16.         protected Object doInBackground(Object... params) {  
    17.             for(int i = 0; i < 30;i++){  
    18.                 System.out.println("InnerAsyncTask" + Thread.currentThread().getId());  
    19.                 try {  
    20.                     Thread.sleep(1000);  
    21.                 } catch (InterruptedException e) {  
    22.                     e.printStackTrace();  
    23.                 }  
    24.             }  
    25.             return null;  
    26.         }  
    27.           
    28.     }  
    29. }  

    AsyncTask更新UI
       AsyncTask约定了任务运行完成后的回调方法,该方法并非抽象的,开发人员能够选择性的实现。
        protected void onPostExecute(Result result)
      该方法是执行在主线程的方法
      实例:
          布局:

    1. <Button  
    2.       android:id="@+id/button1"  
    3.       android:layout_width="wrap_content"  
    4.       android:layout_height="wrap_content"  
    5.       android:layout_alignParentTop="true"  
    6.       android:layout_centerHorizontal="true"  
    7.       android:layout_marginTop="104dp"  
    8.       android:onClick="doAsyncTask"  
    9.       android:text="開始" />  
    10.   
    11.   <ImageView  
    12.       android:id="@+id/imageView1"  
    13.       android:layout_width="wrap_content"  
    14.       android:layout_height="wrap_content"  
    15.       android:layout_below="@+id/button1"  
    16.       android:layout_centerHorizontal="true"  
    17.       android:layout_marginTop="22dp"  
    18.       android:src="@drawable/abs" />  

    MainActivity:

    1.    public class MainActivity extends Activity {  
    2.     private ImageView image;  
    3.     @Override  
    4.     protected void onCreate(Bundle savedInstanceState) {  
    5.         super.onCreate(savedInstanceState);  
    6.         setContentView(R.layout.activity_main);  
    7.          image = (ImageView) findViewById(R.id.imageView1);   
    8. //      System.out.println("onCreate" + Thread.currentThread().getId());  
    9.     }  
    10.       
    11.     public void doAsyncTask(View view){  
    12.         new InnerAsyncTask().execute("");  
    13.     }  
    14.     private class InnerAsyncTask extends AsyncTask<String,Integer, Bitmap>{  
    15.   
    16.         @Override  
    17.         protected Bitmap doInBackground(String... params) {  
    18.             try {  
    19.                 Thread.sleep(3000);  
    20.             } catch (InterruptedException e) {  
    21.                 // TODO Auto-generated catch block  
    22.                 e.printStackTrace();  
    23.             }  
    24.             return BitmapFactory.decodeResource(getResources(), R.drawable.abc);  
    25.         }  
    26.           @Override  
    27.         protected void onPostExecute(Bitmap result) {  
    28.             image.setImageBitmap(result);         
    29.         }  
    30.     }  
    31.   
    32. }  

     AsyncTask更新进度
             AsyncTask约定了任务运行过程中,更新进度的回调方法,该方法并非抽象的,开发人员能够选择性地实现。
    protected void onProgressUpdate(Progress... values)(该方法执行在主线程)
    在任务运行过程中,能够调用publishProgress()方法提交进度,使得onProgressUpdate()方法被回调


        实例
            布局:

    1.  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent" >  
    5.     <TextView   
    6.         android:id="@+id/tv_pb"  
    7.         android:layout_width="wrap_content"  
    8.         android:layout_height="wrap_content"  
    9.         android:text="100%"  
    10.         android:visibility="gone"  
    11.         android:textSize="16sp"/>  
    12.   
    13.     <Button  
    14.         android:id="@+id/btn_update"  
    15.         android:layout_width="wrap_content"  
    16.         android:layout_height="wrap_content"  
    17.         android:layout_alignParentTop="true"  
    18.         android:layout_centerHorizontal="true"  
    19.         android:layout_marginTop="104dp"  
    20.         android:onClick="doAsyncTask"  
    21.         android:text="開始" />  
    22.   
    23.     <ImageView  
    24.         android:id="@+id/iv_image"  
    25.         android:layout_width="wrap_content"  
    26.         android:layout_height="wrap_content"  
    27.         android:layout_below="@+id/btn_update"  
    28.         android:layout_centerHorizontal="true"  
    29.         android:layout_marginTop="22dp"  
    30.         android:src="@drawable/abs" />  
    31.   
    32.     <ProgressBar  
    33.         android:id="@+id/pb_progress"  
    34.         style="?android:attr/progressBarStyleHorizontal"  
    35.         android:layout_width="fill_parent"  
    36.         android:layout_height="wrap_content"  
    37.         android:layout_alignParentTop="true"  
    38.         android:max="100"  
    39.         android:visibility="gone"  
    40.         android:layout_alignRight="@+id/btn_update"  
    41.         android:layout_marginTop="32dp" />  
    42.    
    43. </RelativeLayout>  

          LoadImage:

    1. public class LoadImage extends AsyncTask<String, Integer, Object> {  
    2.   
    3.     private Context context;  
    4.     private ImageView imageview;  
    5.     private Bitmap image;  
    6.     private Button button;  
    7.     private ProgressBar pg;  
    8.     private TextView tv;  
    9.   
    10.     public LoadImage(Context context, Button button, ImageView imageview,  
    11.             ProgressBar pg, TextView tv) {  
    12.         this.context = context;  
    13.         this.imageview = imageview;  
    14.         this.button = button;  
    15.         this.pg = pg;  
    16.         this.tv = tv;  
    17.     }  
    18.   
    19.     @Override  
    20.     protected Object doInBackground(String... params) {  
    21.         for (int i = 0; i <= 100; i++) {  
    22.             publishProgress(i);  
    23.         try {  
    24.             Thread.sleep(50);  
    25.         } catch (InterruptedException e) {  
    26.             // TODO Auto-generated catch block  
    27.             e.printStackTrace();  
    28.         }  
    29.         }  
    30.         image = BitmapFactory.decodeResource(context.getResources(),  
    31.                 R.drawable.abc);  
    32.         return null;  
    33.     }  
    34.   
    35.     @Override  
    36.     protected void onProgressUpdate(Integer... values) {  
    37.         // TODO Auto-generated method stub  
    38.         pg.setProgress(values[0]);  
    39.         tv.setText(values[0] + "%");  
    40.     }  
    41.     @Override  
    42.     protected void onPostExecute(Object result) {  
    43.         imageview.setImageBitmap(image);  
    44.         button.setEnabled(true);  
    45.         pg.setVisibility(View.GONE);  
    46.         tv.setVisibility(View.GONE);  
    47.     }  
    48.   
    49. }  

    MainActivity:

    1.  public class MainActivity extends Activity {  
    2.     private ImageView image;  
    3.     private Button button;  
    4.     private ProgressBar pg;  
    5.     private TextView tv;   
    6.     @Override  
    7.     protected void onCreate(Bundle savedInstanceState) {  
    8.         super.onCreate(savedInstanceState);  
    9.         setContentView(R.layout.activity_main);  
    10.          image = (ImageView) findViewById(R.id.iv_image);     
    11.          button = (Button) findViewById(R.id.btn_update);  
    12.          pg = (ProgressBar) findViewById(R.id.pb_progress);  
    13.          tv = (TextView) findViewById(R.id.tv_pb);  
    14.            
    15.     }  
    16.       
    17.     public void doAsyncTask(View view){  
    18.         button.setEnabled(false);  
    19.         pg.setVisibility(View.VISIBLE);  
    20.         tv.setVisibility(View.VISIBLE);  
    21.         new LoadImage(this,button,image,pg,tv).execute("");  
    22.     }  
    23.       
    24. }  

     AsyncTask是一个综合了任务的运行、进度更新、结果提交的类,使用AsyncTask
           能够集中的编写某个异步任务的所有代码,而不必关心线程间的通信问题。减少了
           编码出错几率,并有效的提高了代码的可阅读性、可维护性等。




           小案例之异步载入图片
                   使用到的技术: Canvas(画布)、Paint(画笔)
    Canvas(画布):用来决定画布的基础属性,运行绘制
    Paint(画笔):设置颜色、设置字体、其它的设置
        同一次画图过程中,可能须要多个画笔对象,或多次调整画笔的属性
        使用Canvas:
                 public Canvas()
        public Canvas(Bitmap bitmap)
        public void drawRect(float left,float top,float right,float bottom,Paint paint)
        public void drawBitmap(Bitmap bitmap,float left,float top,Paint paint)
        public void drawText(String text,float x,float y,Paint paint)
    使用Paint:
        public Paint()
        public native void setColr(int color)
        public native void setAntiAlias(boolean aa)
        public native void setTextSize(float textSize)
        public void setTextAlign(Align align)
        public Xfermode setXfermode(Xfermode xfermode)

  • 相关阅读:
    Android游戏开发22:Android动画的实现J2me游戏类库用于Android开发
    android sqlite SQLiteDatabase 操作大全 不看后悔!必收藏!看后精通SQLITE (第三部分,完整代码)
    使用OGR创建dxf格式矢量数据
    mysql 数据库引擎 MyISAM InnoDB 大比拼 区别
    android sqlite SQLiteDatabase 操作大全 不看后悔!必收藏!看后精通SQLITE (第二部分)
    mysql 更改数据库引擎
    android sqlite SQLiteDatabase 操作大全 不看后悔!必收藏!看后精通SQLITE (第一部分)
    android 数字键盘使用
    MySQL Innodb数据库性能实践
    eclipse : Error while performing database login with the driver null
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7003516.html
Copyright © 2011-2022 走看看