標籤:android asynctask
.xml代碼如下:
<?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>
.java代碼如下:
package org.lxh.demo;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> {//覆寫如下方法@Overrideprotected 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 "執行完畢!";}@Overrideprotected void onPostExecute(String result) {//任務執行完後執行Hello.this.info.setText(result);}@Overrideprotected void onProgressUpdate(Integer... progress) {//每次更新後的數值Hello.this.info.setText("當前進度為:" + String.valueOf(progress[0]));}}}
安卓--非同步處理工具類(AsyncTask)