用的比较广泛的是在activity里面getWindow().setFlag。
但在activity之外的view就不适合这种方法了,这时可以在LayoutParams设置SECURE属性
//setting the layout parameters
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
isBlockScreenshots?//是否阻止截屏
WindowManager.LayoutParams.FLAG_SECURE //是
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
:
//否
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
//getting windows services and adding the floating view to it
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(floatingView, params);
更新:
int flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
if (keepScreenOn) {//保持屏幕常亮
flags = flags + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
if (blockScreenshots) {//阻止截屏
flags = flags + WindowManager.LayoutParams.FLAG_SECURE;
}
//setting the layout types
int types = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;//Android O以前可用
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
types = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
}
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
types,
flags,//阻止截屏
PixelFormat.TRANSLUCENT);
//getting windows services and adding the floating view to it
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(floatingView, params);
这样便为日后增加新功能留下了空间
更新(2):
其中flags除了保持屏幕常亮和防截屏,还可以有其他属性,可以参考google android developers相关文档,(我之前找到现在没找到)。和activity类似。
这是比较入门的东西,但鉴于我自己想做一个不被截屏的浮窗找不到解决方法,无意中看到params这儿的Flags还是花了一点时间,做个记录,也希望(只是希望)能帮到别人