Android利用反射機(jī)制調(diào)用截屏方法和獲取屏幕寬高的方法
想要在應(yīng)用中進(jìn)行截屏,可以直接調(diào)用 View 的 getDrawingCache 方法,但是這個方法截圖的話是沒有狀態(tài)欄的,想要整屏截圖就要自己來實(shí)現(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)用是會報(bào)錯的。
到此這篇關(guān)于Android利用反射機(jī)制調(diào)用截屏方法和獲取屏幕寬高的方法的文章就介紹到這了,更多相關(guān)android 反射調(diào)用截屏方法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析2. vue實(shí)現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程3. 利用CSS3新特性創(chuàng)建透明邊框三角4. div的offsetLeft與style.left區(qū)別5. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)6. CSS代碼檢查工具stylelint的使用方法詳解7. 使用css實(shí)現(xiàn)全兼容tooltip提示框8. 不要在HTML中濫用div9. html清除浮動的6種方法示例10. 詳解CSS偽元素的妙用單標(biāo)簽之美
