我现在正在使用需要在 AsyncTask 中的 LoadImageFromWeb 处理 ImageView。我没有 AsyncTask 的代码是这样的:
private void satellite() {
// TODO Auto-generated method stub
ImageView imgView =(ImageView)findViewById(R.id.satellite);
Drawable drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
imgView.setImageDrawable(drawable);
}
我已经使用 AsyncTask 制作了一些其他程序,但它不同,因为它只使用字符串,我现在是 ImageView。
我搜索了答案,但他们的方法非常混乱。他们正在使用这样的东西:
public class MainActivity extends Activity {
ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
"Carregando...");
new ImageDownload().execute("");
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
mImgView1.setImageBitmap(bm);
} else {
Toast.makeText(MainActivity.this,
"Não foi possível obter resultados", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
从我在 ImageView 上使用的方法来看,这非常复杂(对我来说)。
我的问题是:除了使用第二个代码之外,还有什么更简单、更容易的方法吗?我试着让它工作,但它没有。我不知道如何在图像方面执行 AsyncTask。我很沮丧。
我在这里先向您的帮助表示感谢 :)