Android利用反射機(jī)制調(diào)用截屏方法和獲取屏幕寬高的方法
想要在應(yīng)用中進(jìn)行截屏,可以直接調(diào)用 View 的 getDrawingCache 方法,但是這個方法截圖的話是沒有狀態(tài)欄的,想要整屏截圖就要自己來實現(xiàn)了。
還有一個方法可以調(diào)用系統(tǒng)隱藏的 screenshot 方法,來進(jìn)行截屏,這種方法截圖是整屏的。通過調(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利用反射機(jī)制調(diào)用截屏方法和獲取屏幕寬高的方法的文章就介紹到這了,更多相關(guān)android 反射調(diào)用截屏方法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis2. Python 忽略文件名編碼的方法3. Java Media Framework 基礎(chǔ)教程4. android studio實現(xiàn)簡單的計算器(無bug)5. 解決vue頁面刷新,數(shù)據(jù)丟失的問題6. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作7. 在Mac中配置Python虛擬環(huán)境過程解析8. 利用單元測試對PHP代碼進(jìn)行檢查9. python excel和yaml文件的讀取封裝10. python如何實現(xiàn)word批量轉(zhuǎn)HTML
