DownloadManager

在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();  
    }  
}
复制代码
posted @   Fredric_2013  阅读(480)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2014-07-02 vCPU估算的几个基本概念
点击右上角即可分享
微信分享提示