How to display alert diaolog(popup) from backgroun

2020-03-07 11:10发布

问题:

I am having a background Service which is not binded to any of the application(or Activity). It's monitoring incoming messages, and on receiving message, I have to show one dialog popup. I have tried defining one method which is for showing alert dialog, but it gives exception as "Can't create handler inside thread that has not called Looper.prepare()" I really don't have any idea regarding how to solve this problem. I have searched many post like this over here but not getting how to resolve this one. Help highly appreciated. Thanks.

回答1:

Create a Handler seperately like this.

private Handler handler = new Handler() {
 @Override
 public void handleMessage(Message msg) {

//Call you method in This one...
 displayDialog(); or whatever method name is
 }
};

Now where you are calling the displayDialog() method or what ever named dialog. replace the following code.

handler.sendEmptyMessage(0);

2nd Posible Solution is :

put your method calling code inside the following:

runOnUiThread(new Runnable(){

public void run(){

//Call the method here
}

});

Hope this helps

Thanks sHaH



回答2:

Might be repeated question

If you want to open a dialog from background service then you can not do but there is a way you can open your activity as dialog from service for more info and code

follow below link

android:chat app popup view