背景:
项目中UI层有SurfaceView,其渲染展示的是摄像机等采集画面,但是测试提了一个问题单,如果在当前页面中跳出到其他页面,会crash,经过log分析,是由于surfaceview 在失去焦点的时候会走到onDestroy方法,也就是surfaceview会失效。
解决思路:surfaceview不失去焦点就可以了,改用悬浮窗实现。
UI层 最主要的页面结构如下:
// 摄像机画面
//叠在摄像机画面上的fragment
页面底层是摄像机画面,叠在上面的是fragment,用 framelayout 作为容器去承载,surfaceview既然要作为悬浮窗中去展示,因为悬浮窗的层级比Activity页面高,所以fragment层页面当然也要放到悬浮窗,否则页面就没法操作了。
1、先检查悬浮窗权限。
if (!Settings.canDrawOverlays(this)) {
//启动权限页面
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
} else {
//添加悬浮窗
addWindowSurfaceView();
}
2、创建悬浮窗。
// add window
private void addWindowSurfaceView() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mRootViewLayout = new RootViewLayout(this);
mRootViewLayout.setOrientation(LinearLayout.VERTICAL);
LayoutInflater.from(this).inflate(R.layout.activity_main, mRootViewLayout);
WindowManager.LayoutParams layoutParams = createDefaultWindowLayoutParams();
windowManager.addView(mRootViewLayout, layoutPara