zoukankan      html  css  js  c++  java
  • 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();  
        }  
    }
  • 相关阅读:
    docker的基本操作
    docker和虚拟化技术的区别
    项目命名规则
    Javascript IE 内存释放
    关于ie的内存泄漏与javascript内存释放
    Java遍历HashMap并修改(remove)
    java 中类的加载顺序
    java类的加载以及初始化顺序 .
    JavaScript也谈内存优化
    JavaScript 的垃圾回收与内存泄露
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4616107.html
Copyright © 2011-2022 走看看