码迷,mamicode.com
首页 > 其他好文 > 详细

DownloadManager

时间:2015-07-02 15:40:07      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

在androi中,volley适合小文件的获取和大并发,如果支持大文件的下载可以用Android原生的DownloadManager。DownloadManager默认支持多线程下载、断点续传等。

基础代码如下:

public class MainActivity extends Activity {

    private DownloadManager manager ;  
    private DownloadCompleteReceiver receiver;  
    private Button downBtn ; 
    private Context mContext;

    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main); 
        mContext = this;
        //获取下载服务  
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new DownloadCompleteReceiver(); 
        registerReceiver(receiver, filter);
        
        downBtn = (Button)findViewById(R.id.button1);  
        downBtn.setOnClickListener(new OnClickListener() {  

            public void onClick(View v) {  
                //创建下载请求  
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse("http://www.bz55.com/uploads/allimg/110807/2019341501-0.jpg"));
                
                request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
                
                //定义notification提示
                request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
                request.setTitle("下载");
                request.setDescription("壁纸正在下载");              
                //在onclick中无法直接通过this取到Context上下文
                request.setDestinationInExternalFilesDir(mContext, null, "test_download");
                manager =(DownloadManager)getSystemService(DOWNLOAD_SERVICE); 
                
                manager.enqueue(request);
            }  
        });  
    } 
    
    //接受下载完成后的intent  
    class DownloadCompleteReceiver extends BroadcastReceiver {  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){  
                Toast.makeText(context, "download complete", Toast.LENGTH_SHORT).show();  
            }  
        }  
    }  
            
    @Override  
    protected void onDestroy() {  
        if(receiver != null){ 
            unregisterReceiver(receiver); 
        }
        super.onDestroy();  
    }  
}

DownloadManager

标签:

原文地址:http://www.cnblogs.com/Fredric-2013/p/4616107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!