0

So i was searching for a way to take a screenshot without root i found this question stackoverflow question

mr Robin who answered this question said " you can only get the screen shot of your own process"

1- yes i want to take a screen shot for my own presses may anyone provide some code that does not require root ?

2- my idea is to make a transparent activity and then use the in app screen shot is that possible ?

3- another thing is their is anyway to take a screen shot without root and without being at the foreground ? i had seen many apps on play store that can take a screen shot and does not require root ? any ideas ?

Alexander
  • 113
  • 5

2 Answers2

0

Try this:

public static Bitmap screenshot(final View view) {
    view.setDrawingCacheEnabled(true);
    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
    view.buildDrawingCache();
    if (view.getDrawingCache() == null) {
        return null;
    }

    final Bitmap screenshot = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);
    view.destroyDrawingCache();
    return screenshot;
}

Original code: https://stackoverflow.com/a/5651242/603270

Community
  • 1
  • 1
shkschneider
  • 17,833
  • 13
  • 59
  • 112
0

Considering that we want to take the screenshot when a button is clicked, the code will look like this:

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
       Bitmap bitmap = takeScreenshot();
       saveBitmap(bitmap);
   }
});

First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().

Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking getDrawingCache().

public Bitmap takeScreenshot() {
   View rootView = findViewById(android.R.id.content).getRootView();
   rootView.setDrawingCacheEnabled(true);
   return rootView.getDrawingCache();
}

And the method that saves the bitmap image to external storage:

public void saveBitmap(Bitmap bitmap) {
    File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157