I'm trying to load images in new thread to reduce lags in UI thread:
public class MyGame extends Activity implements Game, Renderer {
...
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
super.onSurfaceCreated(gl, config);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if(firstTimeCreate) {
Settings.load(getFileIO());
// Load bitmaps and save to variable Assets.backgroundRegions
Assets.load(this);
firstTimeCreate = false;
} else {
Assets.reload();
}
}
});
t.start();
}
...
}
The problem is when I trying to draw images as soon as the images is loaded, I only get a white images, no error message. This is the method I use to render background (this method run in a loop)
public void renderBackgrounds() {
if (Assets.backgroundRegions.size() > 0) {
batcher.beginBatch(Assets.backgroundRegions.get(0).texture);
batcher.drawSprite(
Assets.backgroundRegions.get(0).position,
Assets.backgroundRegions.get(0)
);
batcher.endBatch();
} // else { background is not loaded yet }
}
The weird thing is when I press Home button and open my app again, then background images are displayed all correctly. It's just like there are "white-images cached version" of all the loaded images, and Android just don't clear the cache until I re-create the Activity, maybe, I don't know.
If I remove the new thread implementation in onSurfaceCreated like this:
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
super.onSurfaceCreated(gl, config);
if(firstTimeCreate) {
Settings.load(getFileIO());
Assets.load(this);
firstTimeCreate = false;
} else {
Assets.reload();
}
}
...then everything works fine except the UI thread is extremely lag.
I have read some posts about loading Bitmaps in new thread (e.g. this and this), they load Bitmap and assign the variable directly to the View (ImageView), but in my case I save the Bitmap to variables and use OpenGL to render. I don't know if this is one of the reasons or not.
There are the possible reasons I could think about:
- All loaded images are cached wrong (somehow, I don't know) and I only get white images until I re-create the Activity.
- Something wrong with multithreading and the variable I have used to store bitmap data (
backgroundRegions
). - I did things in wrong way when use OpenGL and Multithreading together, I don't know much about OpenGL, the part with OpenGL is taken from a small framework.