Search code examples
androidfilescreenshot

Screen capture file not being saved


According to this link(How to programmatically take a screenshot in Android?), I used the answer to take a capture and save it on my device's external memory.

I have all the permission cleared, and according to the log, the file is not empty at all. But I can't find the file neither on the gallery nor the file explorer.

Why is this happening? Can someone help me out with this?


Solution

  • On regards to Rotwang, I've figured out what the problem was.

    The path of the getExternalStorageDirectory() did not seen to return a valid directory for the file to be saved.

    In my case, it was about saving screenshots for the user to look on the gallery.

    So, I used Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); instead.

    So, the full code for saving a screen capture is below.

     private void takeScreenshot() {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
    
        try {
    
            File path = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
            File file = new File(path, now + ".jpg");
    
            path.mkdirs();
    
            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(file);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();
    
            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.e("ExternalStorage", "Scanned " + path + ":");
                            Log.e("ExternalStorage", "-> uri=" + uri);
                        }
                    });
    
    
        } catch (Throwable e) {
            Log.e("Error", "Exception on TakeScreenshot", e);
        }
    }
    

    Thanks again Rotwang.