Android利用反射機制調用截屏方法和獲取屏幕寬高的方法

想要在應用中進行截屏,可以直接調用 View 的 getDrawingCache 方法,但是這個方法截圖的話是沒有狀態欄的,想要整屏截圖就要自己來實現瞭。

還有一個方法可以調用系統隱藏的 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"/>

調用截屏這個方法需要系統權限,因此沒辦法系統簽名的應用是會報錯的。

到此這篇關於Android利用反射機制調用截屏方法和獲取屏幕寬高的方法的文章就介紹到這瞭,更多相關android 反射調用截屏方法內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: