Screenshot on Android (Phone)

0

I have managed to capture the screen in Android, but it is only the application that invokes it, that is, it does not take the capture of the phone.

//Como se invoca el metodo
capturaPantalla(getWindow().getDecorView());


private File capturaPantalla(View v) {
    View rootview = v.getRootView();
    rootview.setDrawingCacheEnabled(true);
    Bitmap bmp = rootview.getDrawingCache();
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault());
    String fechaComoCadena = sdf.format(new Date());

    File file = new File(Environment.getExternalStorageDirectory() + File.separator + fechaComoCadena + ".jpg");
    try {
        if (file.createNewFile()) {
            try (FileOutputStream outputStream = new FileOutputStream(file)) {
                outputStream.write(bytes.toByteArray());
                outputStream.close();
            }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
    rootview.setDrawingCacheEnabled(false);
    return file;
}

I have searched for information about it but I have not been able to find any satisfactory solution.

    
asked by Cristobal Valenzuela 26.12.2017 в 20:00
source

1 answer

0

This is a response taken from the English OS site that stores the capture on the SD card:

  

link

First you need to enable the permissions to save the file on the card:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

And this is the code:

private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }
}
    
answered by 26.12.2017 в 20:07