安卓中下載圖片有幾種方法?用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進行。