[英]How to return images from asynctask on Android
我正在編寫一個應用程序,在其中構建一個列表視圖,其中每個項目都有一個圖像。 列表視圖的內容由本地存儲的XML文件生成,圖片從Amazon AWS S3中獲取。
我想編寫一個類AWSImageFetcher
,它將首先負責身份驗證(通過使用另一個專用的類),然后負責獲取圖像。
我了解,在此類情況下,最好在Android上將AsyncTask
子類化以執行網絡請求。 我現在不知道我應該怎么從返回的圖像AWSImageFetcher
類列表視圖。
我來自iOS,我將為AWSImageFetcher
編寫一個委托,該AWSImageFetcher
將在獲取圖像后調用,但是在Android上感覺不對。 我應該改用監聽器類嗎? 您將如何以一種優雅的方式在Android上解決這種情況?
試試這個表格
onPreExecute首先在UIThread中執行,之后doInbakground函數在並行線程中執行,然后在UIThread中運行postExecute之后
private class AWSImageFetcher extends AsyncTask<String, Void, Bitmap>
{
boolean authenticated;
@Override
protected void onPreExecute()
{
super.onPreExecute();
authenticated=authenticate();
}
@Override
protected Bitmap doInBackground(String... urls)
{
Bitmap b=null;
if(authenticated)
{
URL imageUrl = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(TIME_OUT_IN_MILLI_SECONDS);
conn.setReadTimeout(TIME_OUT_IN_MILLI_SECONDS);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
b = decodeFile(f);
}
return b;
}
@Override
protected void onPostExecute(Bitmap result)
{
super.onPostExecute(result);
if(result!=null)
{
//use bitmap image in result
}
else
{
//Image is not available
}
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.