Android利用反射機制調(diào)用截屏方法和獲取屏幕寬高的方法
想要在應(yīng)用中進行截屏,可以直接調(diào)用 View 的 getDrawingCache 方法,但是這個方法截圖的話是沒有狀態(tài)欄的,想要整屏截圖就要自己來實現(xiàn)了。
還有一個方法可以調(diào)用系統(tǒng)隱藏的 screenshot 方法,來進行截屏,這種方法截圖是整屏的。
通過調(diào)用 SurfaceControl.screenshot() / Surface.screenshot() 截屏,在 API Level 大于 17 使用 SurfaceControl ,小于等于 17 使用 Surface,但是 screenshot 方法是隱藏的,因此就需要用反射來調(diào)用這個方法。
這個方法需要傳入的參數(shù)就是寬和高,因此需要獲取整個屏幕的寬和高。常用的有三種方法。
獲取屏幕寬高
方法一
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;
反射調(diào)用截屏方法
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 對象就是截取得圖像了。
需要的權(quán)限
<uses-permission android:name="android.permission.READ_FRAME_BUFFER"/>
調(diào)用截屏這個方法需要系統(tǒng)權(quán)限,因此沒辦法系統(tǒng)簽名的應(yīng)用是會報錯的。
到此這篇關(guān)于Android利用反射機制調(diào)用截屏方法和獲取屏幕寬高的方法的文章就介紹到這了,更多相關(guān)android 反射調(diào)用截屏方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android斷點續(xù)傳下載器JarvisDownloader的示例
本篇文章主要介紹了Android斷點續(xù)傳下載器JarvisDownloader的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05Android 標(biāo)準(zhǔn)Intent的使用詳解
這篇文章主要介紹了Android 標(biāo)準(zhǔn)Intent的使用詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03Android Webview添加網(wǎng)頁加載進度條實例詳解
這篇文章主要介紹了Android Webview添加網(wǎng)頁加載進度條實例詳解的相關(guān)資料,需要的朋友可以參考下2016-01-01kotlin object關(guān)鍵字單例模式實現(xiàn)示例詳解
這篇文章主要為大家介紹了kotlin object關(guān)鍵字單例模式實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01Android編程實現(xiàn)捕獲程序異常退出時的錯誤log信息功能詳解
這篇文章主要介紹了Android編程實現(xiàn)捕獲程序異常退出時的錯誤log信息功能,結(jié)合實例形式分析了Android異常信息捕獲與日志操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-08-08