Screen capture from code

2019-03-30 12:25发布

问题:

I need to capture the screen shot of the present screen so I adopted the code below on the

protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

    LinearLayout v = (LinearLayout) findViewById(R.id.mainLayout);
    v.setDrawingCacheEnabled(true);
    // this is the important code :)
    // Without it the view will have a
    // dimension of 0,0 and the bitmap will
    // be null
    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    //v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.layout(0, 0, v.getWidth(), v.getHeight());
    v.buildDrawingCache(true);
    Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false); //

    if (bm != null) {
        try {
            String path = Environment.getExternalStorageDirectory()
                    .toString();
            OutputStream fOut = null;
            File file = new File(path, "screentest.jpg");
            fOut = new FileOutputStream(file);

            bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
            fOut.flush();
            fOut.close();

            Log.e("ImagePath", "Image Path : "
                    + MediaStore.Images.Media.insertImage(
                            getContentResolver(), file.getAbsolutePath(),
                            file.getName(), file.getName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code has worked fine for me but I need to capture the screen just after the screen loading is finished.

I have also tried the onPostCReate() but all goes to vain..

I also tried to call the code in the onPause() method but due to animation, the screen is triming a bit from the right and the bottom portion... so I cant even go for it...

Now its your turn to share your expertise..

Any suggestions are greatly appreciated!!!!

回答1:

Try this:

public void onCreate(Bundle savedInstanceState) {
    LinearLayout v = (LinearLayout) findViewById(R.id.mainLayout);
    v.setDrawingCacheEnabled(true);
    v.post(new Runnable() {
        public void run() {
             // Code to take screenshot
        });
    }

}