在Android中解雇ProgressDialog

时间:2013-08-29 09:15:47

标签: android handler progressdialog ui-thread

我一直想摆脱ProgressDialog一段时间了。经过一些谷歌搜索和阅读stackoverflow上的问题后,我只能从UI线程运行ProgressDialog.dismiss()。经过一些阅读后,我了解到我需要创建一个处理程序并将其附加到UI线程,如下所示:new Handler(Looper.getMainLooper());但是,顽固的ProgressDialog仍然拒绝死亡。

以下是我的代码:

/* Members */
private ProgressDialog mProgressDialog;
private Handler mHandler;

/* Class' constructor method */
public foo() {
    ...
    this.mHandler = new Handler(Looper.getMainLooper());
    ...
}

/* The code that shows the dialog */
public void startAsyncProcessAndShowLoader(Activity activity) {
    ...
    mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
    mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    doAsyncStuff(); // My methods have meaningful names, really, they do
    ...
}

/* After a long process and tons of callbacks */
public void endAsyncProcess() {
    ...
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "Getting rid of loader");
            mProgressDialog.dismiss();
            mProgressDialog = null;
            Log.d(TAG, "Got rid of loader");
        }
    });
    ...
}

这似乎不起作用,调试显示PorgressDialog(mDecor)的某些成员为空。我错过了什么?

3 个答案:

答案 0 :(得分:1)

您应该使用AsyncTask执行异步任务:

AsyncTask task = new AsyncTask<Void, Void, Void>() {
    private Dialog mProgressDialog;

    protected void onPreExecute() {
        mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
        mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    }

    protected Void doInBackground(Void... param) {
        doAsyncStuff(); // My methods have meaningful names, really, they do
        return null;
    }

    protected void onPostExecute(Void result) {
        mProgressDialog.dismiss();
    }
};
task.execute(null);

答案 1 :(得分:0)

progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface dialog) {
    Log.d(TAG, "Got rid of loader");
    }
});

答案 2 :(得分:0)

试试这个:

public static final int MSG_WHAT_DISMISSPROGRESS = 100;
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        swtich(msg.what){
            case MSG_WHAT_DISMISSPROGRESS:
                mProgressDialog.dismiss();
            break;
        }
    }
}

public void endAsyncProcess(){
    handler.obtainMessage(MSG_WHAT_DISMISSPROGRESS).sendToTarget();
}