Android: Screen capturing without root

大兔子大兔子 提交于 2019-12-08 10:04:25

问题


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.

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.


回答1:


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.




回答2:


This won't work in onCreate() because the Activity is visible only after onCreate() is finished. Trigger some event to run your code when onCreate() is finished. May be a onClick() for button event.



来源:https://stackoverflow.com/questions/11078560/android-screen-capturing-without-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!