When my application first starts it needs to do some set up. I’d like to show a progress dialog while this is happening, so the user isn’t just faced with an unresponsive black screen. I am trying to do it with the following code, but the dialog never shows:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shell);
final ProgressDialog dialog = ProgressDialog.show(WhereWolfActivity.this, getString(R.string.loadingtitle), getString(R.string.loading), true, false);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
if(dbHelper == null)
dbHelper = new WhereWolfOpenHelper(getApplicationContext());
checkUserDetails();
String providers = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
checkLocationProviders(providers);
runOnUiThread(new Runnable(){
@Override
public void run() {
dialog.dismiss();
}
});
}
});
thread.start();
}
If I remove dialog.dismiss(); the dialog shows up after the thread is finished. This suggests to me that the UI thread is being blocked. Any ideas how to fix this? Thanks.
Your code works fine on a 2.3.3 Samsung Galaxy S i9000, I just checked (without the DB stuff, obviously – just Thread.sleep() before the runOnUIThread).
Since this answer is not very helpful, let me point you to the class AsyncTask which has been created for the task you are currently doing “by hand”.
Basically, you create a subclass of AsyncTask (as an inner class of your activity) – if you don’t need any parameters, just use Void,Void,Void – and start it in onCreate() with .execute();
Kick off your progress dialog in onPreExecute(), do your background work in doInBackground, and finally dismiss the dialog in onPostExecute(). No fiddling with runOnUIThread.