i have developed a simple AsyncTask class that takes Handlers as its parameters and whilst sending HandlersendEmptyMessage(0) in the doBackground i load up a ProgressDialoge loading view but for some reason it doesnt show until the very end of executing the stuff thats inside my Handler object (in other words the progressDialogue blinks at the end).
here is my AsyncTask:
package com.kc.util;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
public class LoadDialoge extends AsyncTask<Handler, Integer, Void> {
private ProgressDialog progressDialog;
private String TAG = "LoadDialoge";
private Context mContext;
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showWait();
}
@Override
protected Void doInBackground(Handler... params) {
// TODO Auto-generated method stub
for(Handler mHandler : params){
mHandler.sendEmptyMessage(0);
Log.d(TAG, "handler sending message" );
}
return null;
}
private void showWait() {
Log.d(TAG, "showWait");
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Retrieving contact details");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
Log.d(TAG, " ");
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
}
And here is the handler i passed to this class from an Activity:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.d(TAG, "handleMessage");
initialiseOnItemClickListeners();
initialiseOnClickListeners();
initialiseListViewAdapters();
loadDataToDb();
initializeTitles();
initialize();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abstract_main_menu);
LoadDialoge load = new LoadDialoge();
load.setmContext(this);
load.execute(mHandler);
}
Im trying to create a generic Async Load screen that works across any activity that wants to use it instead of copying and pasting the above LoadDialogue AsyncTask across each activity(which i was doing before and worked fine).
Not too surprising it “blinks” is it? Your
doInBackground()does almost nothing at all… the task will complete instantly. Try usingsendEmptyMessageDelayed()instead ofsendEmptyMessage()if you want to fake that there’s actually some processing or waiting going on in your background task.