码迷,mamicode.com
首页 > 移动开发 > 详细

AlertDialog 的context 不能是application的context

时间:2017-07-06 13:22:09      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:get   object   etc   contex   code   create   hardware   nal   manage   

昨天做了一个demo,静态注册的BroadcastrReceiver在onReceive方法里实现 alertdialog.

但是,健哥说我的这个会报错,但是为什么没报错很奇怪,我也很奇怪,今早一来我就研究了一下alertdialog的坑。

dialog 是类型同activity的应用窗口,都可以创建phonewindow实例。

看看dialog的构造函数:

 Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        // 忽略一些代码
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        final Window w = new PhoneWindow(mContext);
        mWindow = w;
        w.setCallback(this);
        w.setOnWindowDismissedCallback(this);
        w.setWindowManager(mWindowManager, null, null);//就是这句话。
        w.setGravity(Gravity.CENTER);

        mListenersHandler = new ListenersHandler(this);
    }

 

setWindowManager(WindowManager wm, IBinder appToken, String appName,  boolean hardwareAccelerated) 第二个参数,我们设为null了。(而在activity中,这个token被设为ActivityThread传过来的token。tockon呢是用来表示窗口的一个令牌,只有符合条件的token才能被WMS通过添加到应用上。)

在Dialog的show方法中,

public void show() {
        // 忽略一些代码
        mDecor = mWindow.getDecorView();

        WindowManager.LayoutParams l = mWindow.getAttributes();
         // 忽略一些代码
        try {
            mWindowManager.addView(mDecor, l);//返回manager的时候,如果tockon不为空会调用getSystemService(),为空会报出异常。
mShowing = true; sendShowMessage(); } finally { } }

 

public Object getSystemService(@ServiceName @NonNull String name) {
        if (getBaseContext() == null) {
            throw new IllegalStateException(
                    "System services not available to Activities before onCreate()");
        }//因为一直传过来的context的tocken

        if (WINDOW_SERVICE.equals(name)) {
            return mWindowManager;
        } else if (SEARCH_SERVICE.equals(name)) {
            ensureSearchManager();
            return mSearchManager;
        }
        return super.getSystemService(name);
    }

 

系统对TYPE_APPLICATION类型的窗口,要求必需是Activity的Token,不是的话系统会抛出BadTokenException异常。Dialog 是应用窗口类型,Token必须是Activity的Token。

 

AlertDialog 的context 不能是application的context

标签:get   object   etc   contex   code   create   hardware   nal   manage   

原文地址:http://www.cnblogs.com/vitabebeauty/p/7125669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!