简体   繁体   English

Android:无需root用户即可进行屏幕捕获

[英]Android: Screen capturing without root

I tried below code but as I run it gives a black screen image on android mobile and on emulator it gives a file, by opening this file I get message as preview not available . 我尝试下面的代码,但是当我运行它时,它在android mobile上提供了黑屏图像,在模拟器上它给出了一个文件,通过打开该文件,我得到消息,因为预览不可用

View v = activity.getWindow().getDecorView();

    v.setDrawingCacheEnabled(true);
    v.destroyDrawingCache();

    int width = activity.getWindowManager().getDefaultDisplay().getWidth();
    int height = activity.getWindowManager().getDefaultDisplay().getHeight();
    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
             MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    v.layout(0, 0, width, height); 

    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false); // clear drawing cache

    FileOutputStream fos = null;
    File fTree = new File(sdCardRoot,"/fi.png");
    fTree.createNewFile();

    try {

        fos = new FileOutputStream(fTree,true);
        if (null != fos) {
            b.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.flush();
            fos.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Please somebody help. 请有人帮忙。 Thank you. 谢谢。

Okay then. 好吧。 You might have to override the below method. 您可能必须重写以下方法。 The problem is because your view is not created yet and even before that you are trying to get the background which is actually not existing and hence you dont get any image. 问题是因为尚未创建视图,甚至在此之前,您都试图获取实际上不存在的背景,因此没有任何图像。

Try this, 尝试这个,

 @Override 
public void onWindowFocusChanged(boolean hasFocus) 
{ 
   // add the entire code for getting the background within this and it will work 
} 

This method gets called, once your view is drawn and hence you will get the required output by overriding this method. 一旦绘制了视图,便会调用此方法,因此您将通过覆盖此方法来获得所需的输出。

This won't work in onCreate() because the Activity is visible only after onCreate() is finished. 这在onCreate()中不起作用,因为仅在onCreate()完成后才可见Activity。 Trigger some event to run your code when onCreate() is finished. onCreate()完成时触发一些事件以运行您的代码。 May be a onClick() for button event. 可能是按钮事件的onClick()。

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

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