我正在使用Universal Image Loader库从网络上异步加载图片。
我想将图像存储在磁盘缓存中而不显示它们,这样即使用户离线,图像仍然可以在必要时在本地使用。
那么,如何在不显示图像的情况下将图像保存在缓存中呢?
我试过这个,但似乎没有用:
DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
ImageLoader.getInstance().loadImage(url, opts, null);
答案 0 :(得分:0)
我使用了一个名为钽的库。它是J2ME和Android的跨平台库。它具有出色的缓存机制。您可以将它用于您的应用程序。更多细节可以在 -
找到答案 1 :(得分:0)
答案 2 :(得分:-1)
Universal Image Loader库的主要思想是在View中异步下载图像并显示它们。兑现是图书馆的特色之一。如果您需要在不显示图像的情况下缓存图像,则不应使用Universal Image Loader。只需编写一个简单的AsyncTask类,它将图像下载到磁盘。 下面是下载图像的函数示例,只需在AsyncTask的doInBackGround中为要下载的所有图像调用它。
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try
{
URL url = new URL(downloadUrl); //you can write here any link
File myDir = new File("/sdcard"+"/"+Constants.imageFolder);
//Something like ("/sdcard/file.mp3")
if(!myDir.exists()){
myDir.mkdir();
Log.v("", "inside mkdir");
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = imageName;
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
/*
* Define InputStreams to read from the URLConnection.
*/
// InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = inputStream.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
}