Question

In my activity i load some data from a web service, during this i show a ProgressDialog to user ... i want the user to be able to close the Activity on pressing BACK D-Pad key. I have done it as follows:

public class MyActivity implements OnCancelListener {
    /*  ...  */

    public void startDialog() {
        ProgressDialog pd = ProgressDialog.show(
            MyActivity.this,    // Context
            "",                 // title for dialog
            "Loading...",       // message for dialog
            true,               // indeterminate?
            true,               // cancellable?
            this                // onCancelListener()
        );
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        // I want to finish() this activity when dialog is canceled
        finish();
    }
}

You can see that i am finishing current activity in onCancel() method of Dialog's OnCancelListener interface. But this method is not called when i press BACK during the dialog is visible. The dialog disappears but onCancel is not called.

Y?

Was it helpful?

Solution

Perhaps it's android restriction. Try it using handler

public class MyActivity implements OnCancelListener {
    /*  ...  */

    private Handler mHandler = new Handler(){

        @Owerride
        public void handleMessage(Message message) {
        switch (message.what) {
        case 1:{
            finish();
        } break;
            }
        }
    };

    public void startDialog() {
        ProgressDialog pd = ProgressDialog.show(
            MyActivity.this,    // Context
            "",                 // title for dialog
            "Loading...",       // message for dialog
            true,               // indeterminate?
            true,               // cancellable?
            this                // onCancelListener()
        );
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        mHandler.sendEmptyMessage(1);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top