Android DownloadManager 使用

Aandroid 3.2 加入了DownloadManager ,这里举例使用方法。

layout添加两个个button,两个txtview

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <Button 
        android:id="@+id/start" 
        android:text="Start Download" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:onClick="startDownload" 
    /> 
    <Button 
        android:id="@+id/query" 
        android:text="Query Status" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:onClick="queryDownloadStatus" 
 
    /> 
    <Button 
        android:id="@+id/del" 
        android:text="del download" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:onClick="delDownloads" 
 
    /> 
  
    <TextView  android:id="@+id/tvsize" 
        android:text="file" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" />   
 
 <TextView  android:id="@+id/tvinfo" 
        android:text="file" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 
</LinearLayout>
package com.download; 
 
 
import android.app.Activity; 
import android.app.DownloadManager; 
import android.app.DownloadManager.Request; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class DWManagerThread extends Activity { 
 
    private DownloadManager mgr=null; 
    private long lastDownload=-1L; 
  
        TextView tvdwsize ;  
        TextView tvdwinfo=null; 
 
    private String strUrl="http://dl.google.com/android/ndk/android-ndk-r6-linux-x86.tar.bz2"; 
    public static final int MSG_DWPACKSIZE=1; 
    public static final int MSG_DWSIZE=2; 
 

    Handler handler= new Handler(){ 
    public void handleMessage (Message msg) { 
       // bar.incrementProgressBy(5); 
        switch(msg.what){ 
                case MSG_DWPACKSIZE: 
                    String  size=String.valueOf(msg.arg1); 
                      tvdwinfo.setText(size); 
                     Log.d("handleMessage", "dwpacksize="+size); 
                    break; 
                case MSG_DWSIZE: 
                    String dwsize=String.valueOf(msg.arg1); 
                    tvdwsize.setText(dwsize); 
                     Log.d("handleMessage", "dwsize="+dwsize); 
                    break; 
                default: 
                    break; 
        } 
 
   } 
}; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
 
  
        tvdwsize=(TextView)findViewById(R.id.tvsize);  
        tvdwinfo=(TextView)findViewById(R.id.tvinfo); 
 
        mgr=(DownloadManager)getSystemService(DOWNLOAD_SERVICE); 
 
    } 
 
 
    public void startDownload(View v) { 
        Uri uri=Uri.parse(strUrl); 
 
        Environment 
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
            .mkdirs(); 
 
        Request dwreq=new DownloadManager.Request(uri); 
 
        dwreq.setTitle("Demo"); 
        dwreq.setDescription("android-ndk-r6-linux-x86.tar.bz2"); 
//把文件存放在 sdcard中的根目录    dpath设置为null 下载到cache
Uri dpath= Uri.fromFile(new File("/mnt/sdcard"+"/crane_evb_v13-ota-20120717.zip"));                
        dwreq.setDestinationUri(dpath);
//要下载到指定目录不能要这句 
//dwreq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"android-ndk-r6-linux-x86.tar.bz2"); 
//dwreq.setDestinationInExternalFilesDir(this, "system", "crane_evb_v13-ota-20120717.zip");      
dwreq.setNotificationVisibility(0); 
        dwreq.setShowRunningNotification(true); 
 
        lastDownload=mgr.enqueue(dwreq);  
 
 
    } 
 
 
public void queryDownloadStatus(View v)  { 
 
      Runnable queryRunable = new Runnable() { 
          long totalsize=0; 
          long dowsize=0; 
          boolean downok=false; 
          Cursor c=null; 
 
        public void run() { 
 
           //查询下载文件总大小 
        	 c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload)); 
        	 c.moveToFirst();
            totalsize=c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); 
 
            Message msg_packsize=new Message(); 
            msg_packsize.what=MSG_DWPACKSIZE; 
            msg_packsize.arg1=(int) totalsize; 
            handler.sendMessage (msg_packsize); 
 
            while(downok==false){ 
                         c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload)); 
 
                        if (c==null) { 
                            //tvdwsize.setText("query=null"); 
                        } 
                        else { 
                            c.moveToFirst(); 
                            //查询已经下载的大小 
                            dowsize=c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); 
                            if(totalsize==dowsize) downok=true; 
                        } 
 
                        Message msg=new Message(); 
                        msg.what=MSG_DWSIZE; 
                        msg.arg1=(int) dowsize; 
                        handler.sendMessage (msg); 
 
                        try { 
                            Thread.sleep(5000); 
                        } catch (InterruptedException e) { 
                            // TODO Auto-generated catch block 
                            e.printStackTrace(); 
                        } 
                        c.close(); 
                } 
            }//run 
        }; 
 
           Thread background = new Thread(queryRunable); 
           background.start(); 
} 
 
    public void delDownloads(View view) { 
 
        Toast.makeText(this, "delDownloads", Toast.LENGTH_LONG).show(); 
        mgr.remove(lastDownload); 
 
 
   } 
//查看下载窗口
    public void viewDownWindow(View v) { 
        startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)); 
    } 
 
 
}

权限:

<uses-permission android:name="android.permission.INTERNET" />  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
 

本文出自 “lhc180” 博客,请务必保留此出处http://lhc180.blog.51cto.com/316940/762122

相关推荐