现在的位置: 首页 > 综合 > 正文

异歩处理工具类

2018年03月31日 ⁄ 综合 ⁄ 共 2073字 ⁄ 字号 评论关闭

 

如果使用Handler,那么需要通过子线程带出Message,要是通过异歩处理类,就可以在异步处理类

中的指定方法中直接更新UI组件。

 

 

 

 

在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"

  android:gravity="center_horizontal"

  android:background="#000000">

  <ProgressBar

     android:id="@+id/bar"

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:layout_margin="8dp"

     style="?android:attr/progressBarStyleHorizontal"/>

  <TextView

     android:id="@+id/info"

     android:layout_margin="8dp"

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:textColor="#ffffff"/>

</LinearLayout>

 

 

 

 

 

在MyAsyncTask.xml中:

 

package com.e.myasynctask;

 

import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.widget.ProgressBar;

import android.widget.TextView;

 

public class MyAsyncTask extends Activity {

  private ProgressBar bar = null;

  private TextView info = null;

 

  @Override

  public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     super.setContentView(R.layout.main);

     this.bar = (ProgressBar) super.findViewById(R.id.bar);

     this.info = (TextView) super.findViewById(R.id.info);

     ChildUpdate child = new ChildUpdate() ;

     child.execute(100) ;

  }

 

  // 每次处理后台进度的类型是Integer、更新之后的数值Integer,最后的结果返回的是字符串

  private class ChildUpdate extends AsyncTask<Integer, Integer, String> {

 

     @Override

     protected void onPostExecute(String result) {

       MyAsyncTask.this.info.setText(result) ;

     }

 

     @Override

     protected void onProgressUpdate(Integer... values) {  // 每次更新之后的内容

       MyAsyncTask.this.info.setText("当前的进度值是:" + String.valueOf(values[0])) ;

     }

 

     @Override

     protected String doInBackground(Integer... params) { // 每次的进度处理,可以更新UI组件

       for (int x = 0; x < 100; x++) {

         MyAsyncTask.this.bar.setProgress(x); // 设置进度

         this.publishProgress(x) ; // 更新,调用更新操作

         try {// 延迟的操作由外部决定

            Thread.sleep(params[0]);

         } catch (InterruptedException e) {

         }

       }

       return "执行完毕";

     }

 

  }

}

 

抱歉!评论已关闭.