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

图片

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

文件

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

如果自己加载的话,需要自己写网络去请求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进行。

用httpclient下载,用universal-image-loader框架下载。必须先下载才能读取文件。

安卓 有自带的http 的包,直接用