欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中使用AsyncTask做下载进度条实例代码

程序员文章站 2023-12-20 20:15:04
android asynctask做下载进度条 asynctask是个不错的东西,可以使用它来做下载进度条。代码讲解如下: package com.exam...

android asynctask做下载进度条

asynctask是个不错的东西,可以使用它来做下载进度条。代码讲解如下:


package com.example.downloadfile; 
 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.inputstream; 
import java.net.httpurlconnection; 
import java.net.url; 
 
import android.app.activity; 
import android.app.dialog; 
import android.app.progressdialog; 
import android.os.asynctask; 
import android.os.bundle; 
import android.os.environment; 
import android.util.log; 
import android.widget.textview; 
 
public class downloadfile extends activity { 
   
  public static final string log_tag = "test"; 
   
    private progressdialog mprogressdialog; 
  public static final int dialog_download_progress = 0; 
   
   
  file rootdir = environment.getexternalstoragedirectory(); 
   
  //定义要下载的文件名 
  public string filename = "test.jpg"; 
  public string fileurl = "https://lh4.googleusercontent.com/-hijoyupc-tq/tgndx1_hdzi/aaaaaaaaawo/deeotnrimak/s800/dsc04158.jpg"; 
   
  @override 
  public void oncreate(bundle savedinstancestate)  
  { 
    super.oncreate(savedinstancestate); 
     
    setcontentview(r.layout.main); 
    textview tv = new textview(this); 
    tv.settext("android download file with progress bar"); 
   
    //检查下载目录是否存在  
    checkandcreatedirectory("/mydownloads"); 
     
    //执行asynctask 
    new downloadfileasync().execute(fileurl); 
  } 
  
   
  class downloadfileasync extends asynctask<string, string, string> { 
     
    @override 
    protected void onpreexecute() { 
      super.onpreexecute(); 
      showdialog(dialog_download_progress); 
    } 
 
     
    @override 
    protected string doinbackground(string... aurl) { 
 
      try { 
        //连接地址 
        url u = new url(fileurl); 
        httpurlconnection c = (httpurlconnection) u.openconnection(); 
        c.setrequestmethod("get"); 
        c.setdooutput(true); 
        c.connect(); 
         
        //计算文件长度 
        int lenghtoffile = c.getcontentlength(); 
         
         
        fileoutputstream f = new fileoutputstream(new file(rootdir + "/my_downloads/", filename)); 
      
        inputstream in = c.getinputstream(); 
 
        //下载的代码 
        byte[] buffer = new byte[1024]; 
        int len1 = 0; 
        long total = 0; 
         
        while ((len1 = in.read(buffer)) > 0) { 
          total += len1; //total = total + len1 
          publishprogress("" + (int)((total*100)/lenghtoffile)); 
          f.write(buffer, 0, len1); 
        } 
        f.close(); 
         
      } catch (exception e) { 
        log.d(log_tag, e.getmessage()); 
      } 
       
      return null; 
    } 
     
    protected void onprogressupdate(string... progress) { 
       log.d(log_tag,progress[0]); 
       mprogressdialog.setprogress(integer.parseint(progress[0])); 
    } 
 
    @override 
    protected void onpostexecute(string unused) { 
      //dismiss the dialog after the file was downloaded 
      dismissdialog(dialog_download_progress); 
    } 
  } 
   
   
  public void checkandcreatedirectory(string dirname){ 
    file new_dir = new file( rootdir + dirname ); 
    if( !new_dir.exists() ){ 
      new_dir.mkdirs(); 
    } 
  } 
   
    @override 
  protected dialog oncreatedialog(int id) { 
    switch (id) { 
      case dialog_download_progress: //we set this to 0 
        mprogressdialog = new progressdialog(this); 
        mprogressdialog.setmessage("downloading file..."); 
        mprogressdialog.setindeterminate(false); 
        mprogressdialog.setmax(100); 
        mprogressdialog.setprogressstyle(progressdialog.style_horizontal); 
        mprogressdialog.setcancelable(true); 
        mprogressdialog.show(); 
        return mprogressdialog; 
      default: 
        return null; 
    } 
  } 
} 

配置文件

注意打开文件保存权限

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
   package="com.example.downloadfile" 
   android:versioncode="1" 
   android:versionname="1.0"> 
   
  <uses-permission android:name="android.permission.internet" /> 
  <uses-permission android:name="android.permission.write_external_storage" /> 
   
  <uses-sdk android:minsdkversion="4" /> 

  <application android:icon="@drawable/icon" android:label="@string/app_name"> 
    <activity android:name=".downloadfile" 
         android:label="@string/app_name"> 
      <intent-filter> 
        <action android:name="android.intent.action.main" /> 
        <category android:name="android.intent.category.launcher" /> 
      </intent-filter> 
    </activity> 

  </application> 
</manifest> 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:

下一篇: