Android 異步處理工具類(AsyncTask)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" ><ProgressBar android:id="@+id/bar" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal"/> <TextView android:id="@+id/info" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </LinearLayout> </pre>
.java代碼如下:import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;public class Hello extends Activity {
private ProgressBar bar = null;
private TextView info = null;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);//設置休眠時間 } private class ChildUpdate extends AsyncTask<Integer, Integer, String> {
//覆寫如下方法
@Override
protected String doInBackground(Integer... params) {//處理后臺任務
for (int x = 0; x < 100; x++) {
Hello.this.bar.setProgress(x);//進度條設置
this.publishProgress(x);//傳遞每次更新內容
try {
Thread.sleep(params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}} return "執行完畢!"; } @Override protected void onPostExecute(String result) {//任務執行完后執行 Hello.this.info.setText(result); } @Override protected void onProgressUpdate(Integer... progress) {//每次更新后的數值 Hello.this.info.setText("當前進度為:" + String.valueOf(progress[0])); } }
} </pre>
本文由用戶 ecn5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!