Screen capture from code

I need to take a screenshot of the current screen, so I accepted the code below on

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 worked fine for me, but I need to capture the screen right after the screen is loading.

I also tried onPostCReate (), but everything goes in vain.

I also tried calling the code in the onPause () method, but due to the animation, the screen gets a little bit worse on the right and bottom ... so I can’t even go for it ...

Now it's your turn to share your experience.

Any suggestions are welcome !!!!

+4
source share
1 answer

Try the following:

  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
         });
     }

 }
+4
source

Source: https://habr.com/ru/post/1339983/


All Articles