弹出对话框Android从后台线程

问题描述:

我需要一个弹出对话框来显示,当我从不同的线程得到消息,但对话框应该不依赖于活动,即它应该显示对话框的任何焦点屏幕。弹出对话框Android从后台线程

可以这样做吗?因为对话框是按照Activity来处理的,所以我想到了使用一个服务,但是又一次添加了一个线程,我想避免这种情况。

还有其他选择吗?

+0

我相信他试图问这个问题:如何从一个单独的线程中运行的服务启动一个对话框?可能有任何数量的活动正在运行。要显示对话框,您需要指定当前活动。 – 2010-10-13 23:24:28

+0

一种可能的解决方案是使用的活性: http://*.com/posts/3912748/revisions – 2013-01-29 08:10:59

+0

https://*.com/a/29804684/2149195 – RBK 2017-09-12 13:36:11

如果您尝试询问当您的活动不是用户手机上的焦点活动时如何显示对话框,请尝试使用通知。通过不同的应用程序弹出对话框会在用户做其他事情时中断用户。从Android UI guidelines

使用通知系统 - 代替 通知

如果你的后台服务需要不 使用对话框来 通知用户,使用标准 通知系统 - 不要使用 对话框或吐司来通知他们。一个 对话框或吐司将立即采取 焦点和打断用户,采取 注意力从他们在做什么: 用户可以在 键入文字的那一刻对话框 出现的中间,可以在 的意外行为对话。用户习惯于通过 处理通知,并可以通过 下拉 便利性来回复您的 消息。

的指南创建的通知是在这里:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

替代解决方案:

AlertDialog dialog; 
//add this to your code 
    dialog = builder.create(); 
    Window window = dialog.getWindow(); 
    WindowManager.LayoutParams lp = window.getAttributes(); 
    lp.token = mInputView.getWindowToken(); 
    lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; 
    window.setAttributes(lp); 
    window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 
//end addons 
alert.show(); 

如果我理解正确的话,你可以使用一个基类所有活动的

public abstract class BaseActivity extends Activity{ 
    protected static BaseActivity current_context = null; 

    @override 
    protected void onPause(){ 
     current_context = null; 
     super.onPause(); 
    } 

    @override 
    protected void onResume(){ 
     current_context = this; 
     super.onResume(); 
    } 

    public static void showDialog(/*your parameters*/){ 
     //show nothing, if no activity has focus 
     if(current_context == null)return; 
     current_context.runOnUiThread(new Runnable() { 
      @override 
      public void run(){ 
       AlertDialog.Builder builder = 
        new AlertDialog.Builder(current_context); 
       //your dialog initialization 
       builder.show(); 
      } 
     }); 
    } 
} 

在你的线程中显示你的对话框BaseActivity.showDialog(..)但是这种方法不起作用,如果你想要在目标设备的任何活动之上显示对话框。