为了从一个网站上加载几张图片,写了如下代码。
public void connectImgtoView(final int max) {
new Thread(new Runnable() {
@Override
public void run() {
URL url = null;
for (int i = 0; i < max; i++) {
try {
url = new URL(postImgUrl.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
final BufferedInputStream bufferedInputStream
= new BufferedInputStream(url.openStream());
Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close();
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(
bitmap,
(int) (992),
(int) (1403),
true
);
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
postImg[finalI].setImageBitmap(scaledBitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
progressOFF();
}
}).start();
}
虽然这个方法执行的很成功,但是存在一个问题,就是性能速度太慢。
所以我想知道什么方法比这个方法更快。
请帮帮我。
变量描述
postImgUrl:类型是ArrayList,这是我想要的图片的url。
postImg : 类型是ImageView Array,这是布局中存在的ImageView。
尝试将for循环放在 Thread
这样你就可以实例化和工作多个 Threads
同时。
public void connectImgtoView(final int max) {
for (int i = 0; i < max; i++) {
new Thread(new Runnable() {
@Override
public void run() {
URL url = null;
try {
url = new URL(postImgUrl.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
final BufferedInputStream bufferedInputStream
= new BufferedInputStream(url.openStream());
Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close();
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(
bitmap,
(int) (992),
(int) (1403),
true
);
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
postImg[finalI].setImageBitmap(scaledBitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
progressOFF();
}
}).start();
}
}