我正在使用LigGdx框架在Android设备上开发新闻屏幕。新闻Api给了我PNG类型图像的链接。在LibGdx中,我正在创建一个新线程来下载图像并将其转换为精灵。虽然这样做,应用程序在一些电话后被击中。这种情况发生在50%的时间。能告诉我如何避免这种类型的悬挂吗?
private void doIcoItemSetup(){
setIcoItemImage(i);
}
}
private void setIcoItemImage(final int i) {
new Thread(new Runnable() {
/** Downloads the content of the specified url to the array. The array has to be big enough. */
private int download (byte[] out, String url) {
InputStream in = null;
try {
HttpURLConnection conn = null;
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setUseCaches(true);
conn.connect();
in = conn.getInputStream();
int readBytes = 0;
while (true) {
int length = in.read(out, readBytes, out.length - readBytes);
if (length == -1) break;
readBytes += length;
}
return readBytes;
} catch (Exception ex) {
return 0;
} finally {
StreamUtils.closeQuietly(in);
}
}
@Override
public void run () {
byte[] bytes = new byte[200 * 1024]; // assuming the content is not bigger than 200kb.
System.out.println("Testing 1111 " + game.icoItemList.get(i).getImageURL());
int numBytes = download(bytes, game.icoItemList.get(i).getImageURL());
if (numBytes != 0) {
// load the pixmap, make it a power of two if necessary (not needed for GL ES 2.0!)
Pixmap pixmap = new Pixmap(bytes, 0, numBytes);
final int originalWidth = pixmap.getWidth();
final int originalHeight = pixmap.getHeight();
int width = MathUtils.nextPowerOfTwo(pixmap.getWidth());
int height = MathUtils.nextPowerOfTwo(pixmap.getHeight());
final Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat());
potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight());
pixmap.dispose();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
System.out.println("Testing 1111 -------------------------------------------------");
System.out.println("Testing 1111 originalWidth,originalHeight : " + originalWidth + "," + originalHeight );
game.icoItemList.get(i).setIcoItemSprite(new Sprite(new TextureRegion(new Texture(potPixmap), 0, 0, originalWidth, originalHeight)));
}
});
}
}
}).start();
}