Android利用反射機制調用截屏方法和獲取屏幕寬高的方法
想要在應用中進行截屏,可以直接調用 View 的 getDrawingCache 方法,但是這個方法截圖的話是沒有狀態(tài)欄的,想要整屏截圖就要自己來實現了。
還有一個方法可以調用系統(tǒng)隱藏的 screenshot 方法,來進行截屏,這種方法截圖是整屏的。
通過調用 SurfaceControl.screenshot() / Surface.screenshot() 截屏,在 API Level 大于 17 使用 SurfaceControl ,小于等于 17 使用 Surface,但是 screenshot 方法是隱藏的,因此就需要用反射來調用這個方法。
這個方法需要傳入的參數就是寬和高,因此需要獲取整個屏幕的寬和高。常用的有三種方法。
獲取屏幕寬高
方法一
int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
這個方法會提示過時了,推薦后邊兩種。
方法二
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth = dm.widthPixels; int screenHeight = dm.heightPixels;
方法三
Resources resources = this.getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); int screenWidth = dm.widthPixels; int screenHeight = dm.heightPixels;
反射調用截屏方法
public Bitmap screenshot() {
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
String surfaceClassName = "";
if (Build.VERSION.SDK_INT <= 17) {
surfaceClassName = "android.view.Surface";
} else {
surfaceClassName = "android.view.SurfaceControl";
}
try {
Class<?> c = Class.forName(surfaceClassName);
Method method = c.getMethod("screenshot", new Class[]{int.class, int.class});
method.setAccessible(true);
return (Bitmap) method.invoke(null, dm.widthPixels, dm.heightPixels);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
最后返回的 Bitmap 對象就是截取得圖像了。
需要的權限
<uses-permission android:name="android.permission.READ_FRAME_BUFFER"/>
調用截屏這個方法需要系統(tǒng)權限,因此沒辦法系統(tǒng)簽名的應用是會報錯的。
到此這篇關于Android利用反射機制調用截屏方法和獲取屏幕寬高的方法的文章就介紹到這了,更多相關android 反射調用截屏方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android 中 GridView嵌套在ScrollView里只有一行的解決方法
本文給大家?guī)韮煞N有關Android 中 GridView嵌套在ScrollView里只有一行的解決方法,非常不錯,具有參考借鑒價值,感興趣的朋友一起看看吧2016-10-10
Android實現Listview異步加載網絡圖片并動態(tài)更新的方法
這篇文章主要介紹了Android實現Listview異步加載網絡圖片并動態(tài)更新的方法,結合實例形式詳細分析了ListView異步加載數據的操作步驟與具體實現技巧,需要的朋友可以參考下2016-08-08
Android ListView中動態(tài)顯示和隱藏Header&Footer的方法
這篇文章主要介紹了Android ListView中動態(tài)顯示和隱藏Header&Footer的方法及footer的兩種正確使用方法,本文介紹的非常詳細,具有參考借鑒價值,對listview header footer相關知識感興趣的朋友一起學習吧2016-08-08
基于Android SQLiteOpenHelper && CRUD 的使用
本篇文章小編為大家介紹,基于Android SQLiteOpenHelper && CRUD的使用。需要的朋友可以參考一下2013-04-04

