简体   繁体   中英

Taking screenshot and saving into app's own directory

I know this question has been answered, but I would like to get a better explanation as I have tried implementing it but it doesn't seem to work.

I have the following code :

private void takeScreenshot() {

        ContextWrapper cw = new ContextWrapper(getApplicationContext());

        //Get screenshot
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        Date fileName = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", fileName);


        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File image = new File(directory,fileName+".jpg");
        try {
            FileOutputStream fos = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

What I would like to happen is to take a screenshot of the screen, save it to a folder with my app name, and have it be readable by the android phone's gallery. My code does none of the above. I do not see any folder w/ the name of my app when I use file explorer, and it doesn't appear in the gallery as well. It seems it doesn't even save the image. Can you please tell me what is wrong with my code?

The code below creates a directory called "AppName" and then stores the screenshot in that directory. This will be readable by the gallery as well. Your code (and the code below) will not work if you do not have the WRITE_EXTERNAL_STORAGE permission.

        private static File getOutputMediaFile() {
            // To be safe, you should check that the SDCard is mounted
            // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp"); //change to your app name

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");


        return mediaFile;
    }

    private void takeScreenshot(){


    //Get screenshot
    View v1 = getWindow().getDecorView().getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);




    File pictureFile = getOutputMediaFile();


    if (pictureFile == null){


        Log.d(TAG, "error creating media file, check storage permission");

        return;
    }

    try {
        FileOutputStream fos = new FileOutputStream(pictureFile); 
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        bitmap.recycle();
    } catch (FileNotFoundException e) {

        Log.d(TAG, "File not found" + e.getMessage());
    } catch (Exception e) {

        e.printStackTrace();
    }

}

Ensure to add

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

to your manifest and ask for permissions on runtime with

ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    00);

The code finds and/or creates a directory with the app name in the getOutputMediaFile() method, then returns a file in the directory with timestamp as its name. Then in the takeScreenshot() method, the screenshot bitmap is converted to a byte[] and a fileOutputStream is used to write this byte[] to the file returned by getOutputMediaFile() .

The result is a screenshot saved to the gallery in the directory "MyCameraApp" (Change to whatever your app's name is)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM