Android中通过AsyncTask类来制作炫酷进度条的实例教程

2019-12-10 18:02:52王旭

1.先初始化进度条提示对话框。

 builder = new AlertDialog.Builder(
     MainActivity.this);
 LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
 mDialogView = inflater.inflate(R.layout.progress_dialog_layout, null);
 mNumberProgressBar = (NumberProgressBar)mDialogView.findViewById(R.id.number_progress_bar);
 builder.setView(mDialogView);
 mDialog = builder.create();

2.设置按钮点击事件。

 findViewById(R.id.circle_btn).setOnClickListener(new View.OnClickListener(){
   @Override
   public void onClick(View v) {
     dismissDialog();
     mNumberProgressBar.setProgress(0);
     myTask = new MyAsyncTask();
     myTask.execute(qqDownloadUrl);
   }
 });

3.DownloadAsyncTask实现,有点长。

private class DownloadAsyncTask extends AsyncTask<String , Integer, String> {

 @Override
 protected void onPreExecute() {
   super.onPreExecute();
   mDialog.show();

 }

 @Override
 protected void onPostExecute(String aVoid) {
   super.onPostExecute(aVoid);
   dismissDialog();
 }

 @Override
 protected void onProgressUpdate(Integer... values) {
   super.onProgressUpdate(values);

   mNumberProgressBar.setProgress(values[0]);
 }

 @Override
 protected void onCancelled(String aVoid) {
   super.onCancelled(aVoid);
   dismissDialog();
 }

 @Override
 protected void onCancelled() {
   super.onCancelled();
   dismissDialog();
 }

 @Override
 protected String doInBackground(String... params) {
   String urlStr = params[0];
   FileOutputStream output = null;
   try {
     URL url = new URL(urlStr);
     HttpURLConnection connection = (HttpURLConnection)url.openConnection();
     String qqApkFile = "qqApkFile";
     File file = new File(Environment.getExternalStorageDirectory() + "/" + qqApkFile);
     if (file.exists()) {
       file.delete();
     }
     file.createNewFile();
     InputStream input = connection.getInputStream();
     output = new FileOutputStream(file);
     int total = connection.getContentLength();
     if (total <= 0) {
       return null;
     }
     int plus = 0;
     int totalRead = 0;
     byte[] buffer = new byte[4*1024];
     while((plus = input.read(buffer)) != -1){
       output.write(buffer);
       totalRead += plus;
       publishProgress(totalRead * 100 / total);
       if (isCancelled()) {
         break;
       }
     }
     output.flush();
   } catch (MalformedURLException e) {
     e.printStackTrace();
     if (output != null) {
       try {
         output.close();
       } catch (IOException e2) {
         e2.printStackTrace();
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
     if (output != null) {
       try {
         output.close();
       } catch (IOException e2) {
         e2.printStackTrace();
       }
     }
   } finally {
     if (output != null) {
       try {
         output.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return null;
 }
}