美文网首页
StrictMode:非UI的Context来访问UI相关的AP

StrictMode:非UI的Context来访问UI相关的AP

作者: WilsonMing | 来源:发表于2023-07-02 15:54 被阅读0次

    在Android11以上版本,项目开启了严格模式StrictMode下,经常会看到以下报错:

    StrictMode policy violation: 
    android.os.strictmode.IncorrectContextUseViolation: 
    WindowManager should be accessed from Activity or other visual Context. Use an Activity or a Context created with Context#createWindowContext(int, Bundle), 
    which are adjusted to the configuration and visual bounds of an area on screen.
    
    

    这个问题的原因是在StrictMode下,使用了非UI的Context来访问UI相关的API,如ViewConfiguration。这样会导致配置不正确,无法获取到正确的显示参数或窗口参数。

    例如,如果您在Adapter中使用了inflater来加载布局,那么您应该使用Activity的Context而不是Application的Context来创建inflater。

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater inflater;
    
        public ImageAdapter(Context context) {
            inflater = LayoutInflater.from(context); //使用Activity的Context
        }
    
        public View getView (int pos, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate (R.layout.thumbitem, parent, false); //不会报错
                ...
            }
            ...
            return convertView;
        }
    }
    
    

    解决方案是使用UI的Context来访问UI相关的API,有三种解决方案:

    1. Application的context替换使用Activity的context
    2. 通过Application.createWindowContext(Display, int, Bundle)获取UI的context
    3. createConfigurationContext(Configuration)创建的Context

    一、Application的context替换使用Activity的context

    二、通过Application.createWindowContext(Display, int, Bundle)获取UI的context

    官网提供提供了示例解决方案,见地址:

    [Context | Android Developers](https://developer.android.com/reference/android/content/Context#createWindowContext(int,)

    ...
    //重点代码,start
    //anyContext为Application
     final DisplayManager dm = anyContext.getSystemService(DisplayManager.class);
     final Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
     final Context windowContext = anyContext.createDisplayContext(primaryDisplay)
             .createWindowContext(TYPE_APPLICATION_OVERLAY, null);
    //重点代码,end
     final View overlayView = Inflater.from(windowContext).inflate(someLayoutXml, null);
    
     // WindowManager.LayoutParams initialization
     ...
     // The types used in addView and createWindowContext must match.
     mParams.type = TYPE_APPLICATION_OVERLAY;
     ...
    
     windowContext.getSystemService(WindowManager.class).addView(overlayView, mParams);
    
    

    基于方案进行封装,可直接使用Java/Kotlin方法使用:

    /**
         *  兼容Android11以后。无UI Context(Application context)不能获取UI(Activity context)相关资源问题
         * @param context {@link android.app.Application}
         * @return
         */
        private static Context getWindowContext(Context context) {
            if (context instanceof Activity){
                return context;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                final DisplayManager dm = context.getSystemService(DisplayManager.class);
                final Display primaryDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
                return context.createDisplayContext(primaryDisplay)
                            .createWindowContext(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, null);
            }else {
                return context;
            }
        }
    //测试方法
            private void Test(Context context){
        Context windowContext = getWindowContext(context);
     //需要使用Activity的Context
        LayoutInflater inflater = LayoutInflater.from(windowContext);
        //....以下其他逻辑
    
    }
    
    
    /**
     * 兼容Android11以后。无UI Context(Application context)不能获取UI(Activity context)相关资源问题
     * @param context {@link android.app.Application}
     * @return
     */
    fun Context.getWindowContext(context: Context): Context? {
        if (context is Activity) {
            return context
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val dm = context.getSystemService(DisplayManager::class.java)
            val primaryDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY)
            context.createDisplayContext(primaryDisplay)
                .createWindowContext(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, null)
        } else {
            context
        }
    }
    
    

    使用该方法后Android11的设备在严格模式下就不会报android.os.strictmode.IncorrectContextUseViolation: 错误了

    三、createConfigurationContext(Configuration)创建的Context

    目前该方法没有找到官网实现链接,后续补充

    相关文章

      网友评论

          本文标题:StrictMode:非UI的Context来访问UI相关的AP

          本文链接:https://www.haomeiwen.com/subject/blpfudtx.html