您的位置:首页 > 移动开发 > Android开发

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not

2013-06-27 19:53 447 查看
今天敲代码报这样错误Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

事发地点为:

DialogUtil.showNetErrorDialog(getApplicationContext());

从犯:

public static void showNetErrorDialog(final Context ctx) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setMessage("没有网络,前去打通?").setIcon(R.drawable.ic_launcher)
.setCancelable(true);
builder.setPositiveButton("前往", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent wifiSettingsIntent = new Intent(
"android.settings.WIFI_SETTINGS");
ctx.startActivity(wifiSettingsIntent);
}
});
builder.setNegativeButton("拉倒", null);
builder.create().show();
}解决方案:
DialogUtil.showNetErrorDialog(BookDetailActivity.this);需要传入本身的activity.this这个context!
原因不详

类似案件:



自己做一个小程序,给windowManager添加一个view的时候,一直报一个错误:

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

这个错误意思就是 token为空,所以添加不上view,我在网上查相关信息,他们说传入的context对象有问题,但是我反复测试在activity中启动widnow并且添加view是正常的,难道就不能在发起一个广播启动windowManager并且添加view?

 

如果是添加view出错,那就说明应该是windowManager.layoutParams中应该缺少什么参数,结果我在网上查阅了一下,真的是需要在windowManager.layoutParams中添加一些type的,结果自己实验了一下,结果真的可以了 ,具体的代码如下:

 

 

[java] view
plaincopy

/** 

     * @author spring sky 

     * Email vipa1888@163.com 

     * My Name: 石明政 

     * QQ 840950105 

     * @param height  高度 

     * @param width   宽度 

     * @return 

     */  

    private LayoutParams getLayoutParam(int height,int width)  

    {  

        if(wmParam==null)  

        {  

            //为windowManager.layoutParams添加type和flag,这样发送广播才不会出现token is null这样的错误  

            wmParam = new WindowManager.LayoutParams(-1, 4);    

            wmParam.windowAnimations = 0;  

            wmParam.format = PixelFormat.TRANSLUCENT  

                    | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW;  

              

        }  

        wmParam.height = height;  

        wmParam.width = width;  

        return wmParam;  

    }  

这样,在windowManager中添加view就可以了

退堂。。。。。。。。。。。

威武~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐