由于项目涉及到公司的一些重要文件,所以需要禁止截屏,防止信息外漏。
截图工具类
ScreenUtils
public class ScreenUtils {
private ScreenUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获得屏幕高度
*
*@paramcontext
*@return
*/
public static int getScreenWidth(Contextcontext) {
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics =newDisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 获得屏幕宽度
*
*@paramcontext
*@return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics =newDisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
returnoutMetrics.heightPixels;
}
/**
* 获得状态栏的高度
*
*@paramcontext
*@return
*/
public static int getStatusHeight(Context context) {
intstatusHeight = -1;
try{
Class clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
intheight = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
}catch(Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
*
*@paramactivity
*@return
*/
public static Bitmap snapShotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
intwidth =getScreenWidth(activity);
intheight =getScreenHeight(activity);
Bitmap bp =null;
bp = Bitmap.createBitmap(bmp,0,0,width,height);
view.destroyDrawingCache();
return bp;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
*@paramactivity
*@return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame =newRect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width =getScreenWidth(activity);
int height =getScreenHeight(activity);
Bitmap bp =null;
bp = Bitmap.createBitmap(bmp,0,statusBarHeight,width,height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
禁止截图的实现
禁止截图通过对window对象加标志位FLAG_SECURE实现,此标识位的注释如下,
/** Window flag: treat the content of the window as secure, preventing
* it from appearing in screenshots or from being viewed on non-secure
* displays.
*
*
See {@link android.view.Display#FLAG_SECURE} for more details about
* secure surfaces and secure displays.
*/
public static final int FLAG_SECURE = 0x00002000;
使用方式如下:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
转自作者:一点点政府。(感谢前辈)
网友评论