I am facing the issue with displaying progressbar onItem selected in option menu. My code is here:

case R.id.mnuLogout:

                showDialog(Constants.PROGRESS_DIALOG);
                closeOptionsMenu(); 

                             if(MyApp.IsLoggedOut())
                    handler.sendEmptyMessage(Constants.LOGOUT);
                 else
                        handler.sendEmptyMessage(Constants.ERROR_MSG);  

Progressbar is displayed after completion of IsLogged method.

有帮助吗?

解决方案

You're calling get() right after the AsyncTask as executed and lose asynchronous behavior because this method waits until task is finished. You should add all the code in try/catch block to AsyncTask.onPostExecute() method and also dismiss the dialog from this method.

void doLogout() {
    new LogoutTask().execute();
}

void dispatchLogoutFinished() {
    dismissDialog(Constants.PROGRESS_DIALOG);
    if (MyApp.IsLoggedOut()) {
        // do something
    } else {
        // do something else
    }
}

private class LogoutTask extends AsyncTask<Void, Void, Void> {
    protected void onPreExecute() {
        TheActivity.this.showDialog(Constants.PROGRESS_DIALOG);
    }

    protected Void doInBackground(Void... params) {
        return null;
    }

    protected void onPostExecute(Long result) {
        TheActivity.this.dispatchLogoutFinished();
    }
}

And I don't think you need to send messages to the handler. The dispatchLogoutFinished() is executed on the UI thread, so there's no need for synchronization.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top