Popping up a Dialog from a non-UI thread

不打扰是莪最后的温柔 提交于 2019-12-01 17:50:47

You are correct that you cannot perform UI operations from a background thread. The way to do it is to use the Handler that you have already implemented to popup the dialog. So something like:

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case GroupsActivity.DISMISS_PROGRESS_DIALOG:
            //your existing dismiss code
            break;
        case GroupsActivity.CREATE_PROGRESS_DIALOG:
            //create the dialog
            break;
        }
    }
};

Then your run method would be:

public void run() {

    secInf = mGroupId.getSecurityInformation();
    if (secInf.getAdmissionLevel() == CreateGroupDialog.PRIVATE_KEY_ACCESS) {
        // do stuff
        mHandler.sendMessage(Message.obtain(mHandler,
            GroupsActivity.CREATE_PROGRESS_DIALOG));
        // do more stuff
    } else {
        mService.joinGroup(mGroupId);
        // Notifies handler to dismiss ProgresDialog and start activity
        mHandler.sendMessage(Message.obtain(mHandler,
            GroupsActivity.JOIN_SUCCESSFUL));
    }
}

You are correct. Background threads cannot pop up dialogs. What you need is a Handler on your UI thread to pop up the dialog for you.

Although it is not a good idea idea to do it, and this answer is for completeness sake only, showing dialog form non-UI thread is possible.

handlerThread = HandlerThread("myHandlerThread")
handlerThread?.start()
handler1 = Handler(handlerThread?.looper)

handler1?.post {
    AlertDialog
        .Builder(this)
        .setPositiveButton("ok") { dialogInterface: DialogInterface, i: Int -> dialogInterface.dismiss() }
        .create()
        .show()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!