[英]Best way to download images from XML content
我正在設計一個Android應用程序,它將以xml格式顯示一些將從遠程URL檢索到的新聞,例如http://adomain/latest.xml。
XML文件具有以下格式:
<articles>
<article>
<id>6</id>
<title>A sample title</title>
<image>http://adomain/images/anImage.jpg</image>
<lastupdate>1326938231</lastupdate>
<content><![CDATA[Sample content]]></content>
</article>
...
</articles>
我創建了一個Updater Service,它偵聽Connectivity更改,並且當系統通過Internet建立連接時,它將嘗試下載xml文件。 然后解析它並保存數據。 更新程序每10分鍾在一個單獨的線程上運行。
我的問題是:處理圖像的最佳方法是什么?
a)顯示新聞項時是否應該對圖像執行延遲加載
要么
b)解析xml文件時是否應該下載圖像?
我建議在顯示新聞項時進行延遲加載,這樣您就不會使用過多的帶寬(並且可能會給用戶帶來成本)。 如果用戶從不希望查看圖像,則無需下載圖像。
對於圖像,我認為您始終遵循延遲加載,因為圖像加載可能需要一些時間,而且高效的延遲加載器可以幫助您避免將來出現任何內存問題。
只需從XMl中獲取<Image>
標簽數據即可。
String imgURL = your <Image> value;
ImageView imageView = new ImageView(this);
Bitmap bmp = BitmapFactory.decodeStream(new java.net.URL(imgURL).openStream());
imageView.setId(i);
imageView.setImageBitmap(bmp);
這將設置圖像,並且您還將在“ bmp”中獲得圖像。
Android provide directly show image from URL:
要將圖像存儲到SD卡:
File file = new File (pathOfSdCard, iamgeName);
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
將Line放入您的AndroidMenifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我在我的應用程序中使用的所有這些。 它工作正常。
我希望這對您有很大幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.