2015-08-24 35 views
-1

我有一个使用三种活动的应用程序。我在第一个中创建了一个线程来检查与服务器的连接,当应用程序无法到达服务器时,它显示一个Popup。需要在不同的活动上显示弹出式菜单/对话框

问题是,当我从Activity1移动到Activity2并失去连接时,我得到一个WindowManager $ BadTokenException。

我试着用PopupWindow和AlertDialog,但我有同样的问题,我不能给他们当前的活动。

警告对话框:

  AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext()); 
      builder1.setMessage("Se ha hecho el cierre diario, es necesario reiniciar la aplicación."); 
      builder1.setCancelable(true); 
      builder1.setPositiveButton("Ok", 
        new DialogInterface.OnClickListener() 
      { 
       public void onClick(DialogInterface dialog, int id) 
       { 
        java.lang.System.exit(0); 
       } 
      }); 

      AlertDialog alert11 = builder1.create(); 
      alert11.show(); 

PopupWindow:

 final Activity context = Activity_Start.this; 

     final boolean Reset = reset; 

     // Inflate the popup_layout.xml 
     LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup_mensaje_error); 
     LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     final View popup_error = layoutInflater.inflate(R.layout.mensaje_error, viewGroup, false); 

     // Creating the PopupWindow 
     final PopupWindow popupW_error = new PopupWindow(context); 
     popupW_error.setContentView(popup_error); 

在这两种情况下,我有同样的错误,我几乎可以100%肯定是原因getApplicationContext()是没有足以让什么应用程序需要。

有人可以帮助我吗?谢谢!!

+0

使用DialogFragment,你可以附加一个detach到你喜欢的任何活动 – Raghunandan

+0

我认为你的错误驻留在“final Activity context = Activity_Start.this;”你不应该得到像这样的背景 –

+0

Raghunandan,它是如何工作的? Klitos,我应该怎么做? –

回答

0

Android的文件建议使用getApplicationContext();

但使用您的当前活动在实例AlertDialog.Builder或AlertDialog或Dialog它不会工作,而不是...

尝试

AlertDialog.Builder builder1 = new AlertDialog.Builder(Activity_Start.this); 

代替

AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext()); 

,还可以使用的

final Context context = Activity_Start.this; 

代替

final Activity context = Activity_Start.this; 

对话绑定到这个特殊的活动,而不是整个应用程序。当创建范围仅仅是活动的对象时,通常使用Activity.this。在创建范围超出当前活动范围的对象时使用应用程序上下文。

希望这有助于!

+0

是的Rajesh,我有这种方式,问题是线程在Activity1上开始,如果我在Activity2上工作时连接丢失,我不知道如何发送到对话框当前活动。 –

+0

你试过吗? – Rajesh

+0

是的,但我从Activity2调用对话框时得到WindowManager $ BadTokenException。 –