android 介面截圖(目前速度最快)
阿新 • • 發佈:2018-12-17
android 介面截圖不算新鮮事,以前本人也寫過一篇關於螢幕截圖的部落格,當時的需求是整體截圖,然後對特有的區域進行二次截圖,功能算是實現了,體驗不是很好 ,週期太長。雖然使用者感受不到,但是作為一個強迫症的程式設計師。會花時間追求更快的體驗。
以前的截圖是採用anroid Api來呼叫截頻,這次使用adb的方式來截頻,在響應速度上有明顯的提升,大家可以下載試試
先寫一個介面,用來回調截頻的資料
如果第一個引數是true,第二個引數就是圖片的路徑
如果第一個引數是false,第二個引數就是錯誤資訊
public interface CaptureImageListener { void getCaptureImagePath(boolean isSuucess, String imagePath); }
public CaptureUtil(Context context) { this.context = context; } public void captureScreen(CaptureImageListener listener) { MyLog.update("===================開始截圖==" + System.currentTimeMillis()); FileUtil.creatPathNotExcit(); String picPath = AppInfo.BASE_IMAGE + "/capture.png"; File dirFile = new File(picPath); if (!dirFile.exists()) { try { dirFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { //請求root許可權 Process su = Runtime.getRuntime().exec("su"); //以下兩句代表重啟裝置 String strcmd = "/system/bin/screencap -p " + picPath; strcmd = strcmd + "\n exit\n"; OutputStream os = su.getOutputStream(); os.write(strcmd.getBytes()); os.flush(); os.close(); if ((su.waitFor() != 0)) { throw new SecurityException(); } zipImagePath(picPath, listener); } catch (Exception e) { MyLog.update("===截圖失敗==" + e.getMessage()); TcpService.getInstance().isUpdateMirrorImage = false; listener.getCaptureImagePath(false, ""); } MyLog.update("===================截圖結束==" + System.currentTimeMillis()); }
請求root許可權,然後呼叫截圖,儲存,之後進行圖片壓縮,壓縮我使用的是魯班壓縮,需要了解的可以去這裡看看
下面是壓縮方法
private void zipImagePath(String savePath, final CaptureImageListener listner) { MyLog.update("===================開始壓縮==" + System.currentTimeMillis()); File file = new File(savePath); MyLog.update("====壓縮錢檔案的大小==" + file.length()); if (file.length() < (1024 * 100)) { //如果圖片<400KB,不用壓縮,直接返回 MyLog.update("===================不用壓縮==" + System.currentTimeMillis()); listner.getCaptureImagePath(true, savePath); return; } Luban.with(context) .load(savePath) // 傳人要壓縮的圖片列表 .ignoreBy(100) // 忽略不壓縮圖片的大小 .setTargetDir(AppInfo.BASE_CACHE) // 設定壓縮後文件儲存位置,資料夾路徑 .setCompressListener(new OnCompressListener() { //設定回撥 @Override public void onStart() { MyLog.update("========圖片開始壓縮====="); } @Override public void onSuccess(String savePath) { listner.getCaptureImagePath(true, savePath); MyLog.update("===================壓縮success==" + System.currentTimeMillis()); } @Override public void onError(Throwable e) { TcpService.getInstance().isUpdateMirrorImage = false; listner.getCaptureImagePath(false, e.toString()); MyLog.update("===================圖片壓縮failed==" + System.currentTimeMillis()); } }).launch(); //啟動壓縮 }
目前使用的狀態來看,這個還比較快,基本幾毫秒,就可完成截頻壓縮所有的工作,cpu效能差一點的,也就幾十毫秒的差別。