Wednesday, January 9, 2013

[Android] 使用AsyncTask來顯示進度

package com.example.asynctasktest;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AsyncTaskTest extends Activity {
 TextView m_textView;
 TextView m_progress;
 ProgressBar m_progressBar;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_async_task_test);
  m_textView = (TextView) findViewById(R.id.main_text);
  m_progress = (TextView) findViewById(R.id.text_progress);
  m_progressBar = (ProgressBar) findViewById(R.id.progressBar); 

//呼叫AsynceTask來執行背景任務,之後更新使用者介面
  new TextViewChanger().execute();
 }

//變更文字區塊的內容
 private void changeViewText(){
  m_textView.setText(R.string.screen2);
 }

//變更進度文字與進度條
 private void updateProgress(Integer progress){
  String output = String.format("%1$d%% complete", progress * 10);
  m_progress.setText(output);
  m_progressBar.setProgress(progress * 10);
 }

//實作一個TextViewChanger的類別繼承AsyncTask
//可以在背景執行一些工作,執行完之後會作onPostExecute
 private class TextViewChanger extends AsyncTaskInteger
, Void>{   @Override
  protected Void doInBackground(Void... arg0) {
   // TODO Auto-generated method stub
   for(int i = 0; i <= 10; i++){
    publishProgress(i);
    try{
//設定每兩秒更新一次
     Thread.sleep(2000);
    }catch(InterruptedException e){
     e.printStackTrace();
    }
   }
   return null;
  }
 
//當doInBackground呼叫PublishProgress()時會呼叫onProgressUpdate()
  protected void onProgressUpdate(Integer...progress){
   updateProgress(progress[0]);
  }
 
//當背景工作doInBackground()執行完之後呼叫這個函式,可以直接更新UI
  protected void onPostExecute(Void noUse){
   changeViewText();
  }
   
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_async_task_test, menu);
  return true;
 }
}

No comments:

Post a Comment