如何正确调用从广播接收器更改UI的方法?

时间:2011-10-19 18:58:49

标签: java android broadcastreceiver alertdialog

我有一个广播接收器,可以检测拨出电话的结束。在那之后,我想在我的活动中显示一些对话框。我在我的活动中尝试了这种方法:

 public static void buildShouldIFollowMessage(String callLength) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setMessage(Constants.CONN_TIMEOUT_MESSAGE+" "+callLength)
           .setCancelable(false)
           .setPositiveButton("Da", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {


                        //DownloadTask d=new  DownloadTask(); 
                        //d.execute(Constants.WS_ADDRESS);   xmlPredlog.xml                                
               }
           })
           .setNegativeButton("Ne", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {

                    dialog.cancel();
                    //showCustomToast("something");
                    //emptyList.setText("something");
               }
           });
    final AlertDialog alert = builder.create(); 
    alert.show();
  }

Everything编译并运行,但是当调用alert.show()时,我得到“AndroidRuntime(827):引起:android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序”

这里有什么解决方案,对于其他情况,当你必须从广播接收器调用一些活动代码时?

1 个答案:

答案 0 :(得分:0)

来自BroadcastReceiver doc

  

特别是,您可能无法显示对话框或绑定到服务   在BroadcastReceiver中。对于前者,你应该使用   NotificationManager API。对于后者,你可以使用   Context.startService()将命令发送到服务。

因此要么使用通知系统,要么启动看似对话的活动