开发者社区> 问答> 正文

关于安卓下载图片和下载文件的问题

图片

安卓中下载图片有几种方法?用URL下载?

文件

文件都是从服务器中下载下来后解析吗?

展开
收起
爵霸 2016-03-12 11:30:56 1765 0
1 条回答
写回答
取消 提交回答
  • 如果自己加载的话,需要自己写网络去请求url地址进行下载。类似于这样

     URL url = new URL(uri);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(10000);
    
                    if (conn.getResponseCode() == 200) {
                        InputStream fis =  conn.getInputStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] bytes = new byte[1024];
                        int length = -1;
                        while ((length = fis.read(bytes)) != -1) {
                            bos.write(bytes, 0, length);
                        }
                        picByte = bos.toByteArray();
                        bos.close();
                        fis.close();
    
                        Message message = new Message();
                        message.what = 1;
                        handle.sendMessage(message);
                    }
    
    
                }catch (IOException e) {
                    e.printStackTrace();
                }

    第二种就是用开源的一些框架,比如ImageLoader:

     public class ImageLoaderPicture {
    
        private DisplayImageOptions options;
    
        public ImageLoaderPicture(Context context) {
    
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging() 
            .memoryCache(new WeakMemoryCache())                                 
            .build();
            ImageLoader.getInstance().init(config);
    
            options = new DisplayImageOptions.Builder()
            .showStubImage(0)
            .showImageForEmptyUri(0)
            .showImageOnFail(0)
            .cacheInMemory().cacheOnDisc()
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
            .bitmapConfig(android.graphics.Bitmap.Config.RGB_565)
            .build();
        }
    
        public DisplayImageOptions getOptions() {
            return options;
        }
    
        public void setOptions(DisplayImageOptions options) {
            this.options = options;
        }

    最后还可以使用谷歌官方提供的框架Volley进行。

    2019-07-17 19:00:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载