文章轉載只能用於非商業性質,且不能帶有虛擬貨幣、積分、註冊等附加條件。轉載須註明出處:http://blog.csdn.net/flowingflying/async
Progress Dialog小例子ide
咱們經過IReportBack接口隱藏了Activity,可是有時咱們須要彈框等操做,就須要Context。下面的例子是在執行的過程當中彈出Progress Dialog來提示正在處理中。函數
和MyLongTaskTwo相同的處理的代碼將不列出。學習
public class MyLongTaskTwo extends AsyncTask<String,Integer,Integer>{
private IReportBack report = null;
private Context context = null;
private String tag = null;
private ProgressDialog pd = null;
//在AsyncTask中進行彈框處理,須要在構造函數中傳遞Context。
public MyLongTaskTwo(IReportBack inr, Context inCont, String inTag){
report = inr;
context = inCont;
tag = inTag;
}
@Override
protected void onPreExecute() {
pd = ProgressDialog.show(context, tag, "In progress.... "); //顯示進度框,這裏須要context
}
@Override
protected void onProgressUpdate(Integer... values) {
…..
}
@Override
protected void onPostExecute(Integer result) {
……
pd.cancel(); //取消進度框的顯示
}
@Override
protected Integer doInBackground(String... params) {
… …
}
}this
在主線程中AsyncTask的代碼:.net
private void testProgressDialog(){
MyLongTaskTwo task = new MyLongTaskTwo(this, this, "TaskTwo");//傳遞context
task.execute("TaskTwo","File","Edit","Refactor","Source","Navigate", Help");
}線程
上面的進度框不能精確顯示進展狀況,稱爲indeterministic進度框。更多的時候咱們但願能顯示進展程度,這就是deterministic進度框,如圖所示:blog
相關代碼以下:接口
public class MyLongTaskThree extends AsyncTask<String,Integer,Integer>
implements DialogInterface.OnCancelListener{
@Override //ProgressDialog被cancel時觸發的回調函數,處理pd.cancel()會觸發外,若是咱們按了返回鍵,也會觸發onCancel,咱們能夠在此進行關閉async任務的處理,不然任務的worker線程將繼續執行。
public void onCancel(DialogInterface dialog) {
report.reportBack(tag,"Cancel Called");
}
... ...
private ProgressDialog pd = null;
public MyLongTaskThree(IReportBack inr, Context inCont, String inTag,int inLen){
... ...
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle(tag);
pd.setMessage("In progressing");
pd.setCancelable(true);
pd.setOnCancelListener(this); //設置cancel的回調函數
pd.setIndeterminate(false); //代表是個detemininate精確顯示的進度框
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(length);
pd.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
... ...
pd.setProgress(i+1);
}
@Override
protected void onPostExecute(Integer result) {
... ...
pd.cancel();
}
@Override
protected Integer doInBackground(String... params) {
int num = params.length;
for(int i = 0; i < num;i ++){
Utils.sleepForSecs(2);
publishProgress(i);
}
return num;
}
}開發
相關小例子源代碼可在Pro Android學習:AsyncTask小例子中下載。
相關連接: 個人Android開發相關文章