android学习——AsyncTast 异步操作和 ProgressBar


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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button 
	android:id="@+id/btn_net"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="开始执行模拟网络操作"
/>
<Button 
	android:id="@+id/btn_out"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="开始打印操作"
/>
<TextView 
	android:id="@+id/result"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
/>
<ProgressBar 
	android:id="@+id/pro_bar"
	style="?android:attr/progressBarStyleHorizontal"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
/>
<Button 
	android:id="@+id/btn_pro"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="更新进度条"
/>
</LinearLayout>

用来模拟网络操作java

public class NetOperate {

	static public void operate(int sec){
		try {
			//当前线充休眠
			Thread.sleep(sec*1000);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

activity 

public class ProgressAsyncTask extends AsyncTask<Integer, Integer, String>{

	private TextView textView;
	private ProgressBar progressBar;
	
	public ProgressAsyncTask(TextView textView, ProgressBar progressBar) {
		this.textView = textView;
		this.progressBar = progressBar;
	}
	
	//开始执行异步操作时,执行次方法.
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		System.out.println(textView);
		textView.setText("异步操作开始");
	}
	//异步执行的
	@Override
	protected String doInBackground(Integer... params) {
		// TODO Auto-generated method stub
		int i=0;
		for (i=10; i<=100; i+=10) {
			//休眠 
			NetOperate.operate(1);
			//发布一个更新,调用这个方法的同时 执行 onProgressUpdate
			publishProgress(i);
		}
		return i+params[0].intValue()+"";
	}

	//异步操作执行完成后执行该法方法,一般用来返回结果
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		textView.setText("异步操作结束"+result);
	}
	
	//在doInBackground方法中每调用 publishProgress()方法是会自动调用onProgressUpdate()方法
	//在ui线程中执行
	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		progressBar.setProgress(values[0]);
	}
	

结果

android学习——AsyncTast 异步操作和 ProgressBar_第1张图片   mail 

你可能感兴趣的:(exception,android,String,layout,Integer,encoding)