I have an application which loads several resources in memory during startup. Considering this operation takes some time, I'd like to allow the user to make the first interactions with the UI while the startup operations are happening. However, I can't let the user make further interactions with the UI before the resources are completely loaded.
My idea is to structure the activity as follows:
- Code: Select all
public class MyActivity extends Activity {
private LoadThread loadThread;
private class LoadThread extends Thread {
Context context;
public LoadThread(Context context) {
this.context = context;
}
public void run() {
StartupManager.run(context); // Loads main resources (takes some time)
}
}
public void onCreate(Bundle savedInstanceState) {
this.loadThread = new LoadThread(this);
loadThread.run();
// Loads a few basic resources
// Prepares the UI for first interaction
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// The code in here can only run when all resources are loaded,
// so I should join the LoadThread
try {
this.loadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Continue using all the resources
}
}
The user can do a few things before the main resources are loaded, but the code inside onActivityResult requires all resources to be loaded. That's why I thought about joining the LoadThread.
However, my logs show that nothing happens before the LoadThread finishes. Not even the initial UI interactions that I wanted. In fact, the UI does not even appear before the LoadThread finishes. Do you guys know why this happens?
I also thought about using the AsynTask class. As expected, I can do the background tasks inside the method doInBackground. However, I don't know how to block the code inside onActivityResult (which requires all resources) until the method onPostExecute is called. Using Thread#sleep in the main thread is probably not a very good idea.
Any other ideas?
Thanks so much,
Tiago



