简体   繁体   English

以编程方式获取Android屏幕截图-屏幕应用上的所有内容都可能位于后台而非根目录设备中

[英]Take Android Screenshot programmatically-whatever on screen-app may be in background-not rooted device

I want to take Screenshot of Android device programmatically. 我想以编程方式拍摄Android设备的屏幕截图。 I have searched lot of things but wherever i found, it is saying that either your device should be rooted or only you can take screenshot of your app only, ie if your app is in background then it will not take screenshot of home screen. 我已经搜索了很多东西,但是无论我在哪里发现,这都意味着您的设备应该是植根的,或者只有您才能拍摄应用程序的屏幕快照,即,如果您的应用程序在后台,则不会拍摄主屏幕的屏幕快照。

In short, i want screenshot which gives me whatever is on screen that user can seen. 简而言之,我想要屏幕截图,该屏幕截图可以让我看到用户可以在屏幕上看到的任何内容。 My own app may be in background. 我自己的应用程序可能在后台。

  1. Device is not rooted 设备未root
  2. Whole screen(only visible portion to user) 全屏(仅用户可见部分)
  3. App may be in background(but still should take screenshot of whatever visible to user, ie may be home screen) 应用可能在后台(但仍应拍摄用户可见的屏幕截图,即可能是主屏幕)

To get screenshot you need to get root layout of the view 要获取屏幕截图,您需要获取视图的根目录布局

getWindow().getDecorView();

Cache the View into Bitmap 将视图缓存到位图中

public static File getScreenShot(Context context,View parentLayout) 
    {
        parentLayout.setDrawingCacheEnabled(true);
        Bitmap cachedBitmap= parentLayout.getDrawingCache();
        Bitmap finalBitmap = cachedBitmap.copy(Bitmap.Config.RGB_565, true);
            return saveBitmap(context,finalBitmap);
    }

Save the bitmap on the device or such 将位图保存在设备等上

private static File saveBitmap(Context context,Bitmap bitmap) 
    {
        File snapShot=null;
        try 
        {
            String cacheDirectory=getCacheDirectory(context);               
            snapShot=new File(cacheDirectory, "Screenshot.png");
            FileOutputStream out = new FileOutputStream(snapShot);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
        } catch (Exception e) 
        {
               e.printStackTrace();
        }
        return snapShot;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM