1:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <TextView
android:id="@+id/tvInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> <ProgressBar
android:layout_below="@id/tvInfo"
android:id="@+id/asyncPb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
/> </RelativeLayout>
2:MainActivity.java
package com.example.async; import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.Activity; public class MainActivity extends Activity {
private ProgressBar asyncPb = null;
private TextView tvInfo = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tvInfo = (TextView)findViewById(R.id.tvInfo); String params = "Welcome to here";
new MyAsyncTask().execute(params);
} private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected void onPreExecute() {
//做一些预处理
asyncPb = (ProgressBar)findViewById(R.id.asyncPb);
asyncPb.setVisibility(View.VISIBLE);
} @Override
protected String doInBackground(String... params) {
//执行耗时操作,网络任务、文件操作、数据库操作、复杂计算操作
int myProgress = 0;
int length = params[0].length(); for(int i=1; i<=length; i++){
myProgress = i;
//模拟耗时操作
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress((int)((myProgress/(float)length)*100));
} //它将传递给onPostExecute
return params[0];
} @Override
protected void onProgressUpdate(Integer... values) {
//更新进度条
asyncPb.setProgress(values[0]);
tvInfo.setText("已加载:"+(values[0])+"%");
} @Override
protected void onPostExecute(String result) {
//更新UI
tvInfo.setText("加载完成:"+result);
}
}
}