两种方式各有不同,AsyncTask类从操作上更简单并且容易实现,而用第一种方法则要用到4个类:Handler, Message, Looper, Thread类,原因是进度条这种耗时的操作一般要放入子线程处理,而子线程无权改动UI线程的任何组件,只能动过Handler类传递Message来改动
Activity组件准备:
1 public class MainActivity extends Activity { 2 3 private ProgressBar progressBar1 = null; 4 private TextView progressBar1Text = null; 5 private ProgressBar progressBar2 = null; 6 private TextView progressBar2Text = null; 7 private Button startBtn = null; 8 private MyHandler myHandler = null; 9 10 private static final int SETPROGRESS = 1; 11 private static final int FINISH = 2; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 progressBar1 = (ProgressBar) findViewById(R.id.progressBar1); 19 progressBar1Text = (TextView) findViewById(R.id.progressBar1Text); 20 progressBar2 = (ProgressBar) findViewById(R.id.progressBar2); 21 progressBar2Text = (TextView) findViewById(R.id.progressBar2Text); 22 myHandler = new MyHandler(); 23 24 startBtn = (Button) findViewById(R.id.startBtn); 25 startBtn.setOnClickListener(new StartBtnListener()); 26 27 }
开始按钮监听:
1 private class StartBtnListener implements OnClickListener { 2 3 @Override 4 public void onClick(View v) { 5 // 异步处理进度条 6 MyAsyncTask mat = new MyAsyncTask(); 7 mat.execute(100); 8 9 // handler + message 处理进度条 10 new Thread(new MyThread()).start(); 11 } 12 13 }
异步处理类:
AsyncTask<Integer, Integer, String>
第一参数:传入的延时参数; 第二参数:即时进度 ;第三参数:任务结束后的返回值
1 // 使用异步处理工具类完成更新进度条 2 private class MyAsyncTask extends AsyncTask<Integer, Integer, String> { 3 4 @Override 5 protected void onPostExecute(String result) { 6 MainActivity.this.progressBar1Text.setText(result); 7 } 8 9 @Override 10 protected void onProgressUpdate(Integer... values) { 11 MainActivity.this.progressBar1Text.setText("进度: " + values[0]); 12 } 13 14 @Override 15 protected String doInBackground(Integer... params) { 16 for (int i = 0; i < MainActivity.this.progressBar1.getMax(); i++) { 17 MainActivity.this.progressBar1.setProgress(i); 18 // 更新操作,传给onProgressUpdate方法 19 this.publishProgress(i); 20 try { 21 Thread.sleep(params[0]); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } 25 } 26 27 // 传给onPostExecute方法 28 return "执行完毕哦"; 29 } 30 31 }