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