Example usage for android.support.v4.provider DocumentFile fromFile

List of usage examples for android.support.v4.provider DocumentFile fromFile

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile fromFile.

Prototype

public static DocumentFile fromFile(File file) 

Source Link

Usage

From source file:org.dkf.jed2k.android.LollipopFileSystem.java

private static DocumentFile getDocument(Context context, File file) {
    try {//from   ww w  .j  a  va2  s. c  o m
        String path = file.getAbsolutePath();
        String baseFolder = getExtSdCardFolder(context, file);
        if (baseFolder == null) {
            return file.exists() ? DocumentFile.fromFile(file) : null;
        }

        //baseFolder = combineRoot(baseFolder);

        String fullPath = file.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.isEmpty() ? new String[0] : relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        for (int i = 0; i < segments.length; i++) {
            String segment = segments[i];
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                return null;
            }
        }

        return f;
    } catch (Exception e) {
        LOG.error("Error getting document: {} {}", file, e);
        return null;
    }
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getFile(Context context, File file, boolean create) {
    try {/*from w  w  w.j  a v a2  s.  c o  m*/
        String path = file.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null && cached.isFile()) {
            return cached;
        }

        File parent = file.getParentFile();
        if (parent == null) {
            return DocumentFile.fromFile(file);
        }

        DocumentFile f = getDirectory(context, parent, false);
        if (f == null && create) {
            f = getDirectory(context, parent, create);
        }

        if (f != null) {
            String name = file.getName();
            DocumentFile child = f.findFile(name);
            if (child != null) {
                if (child.isFile()) {
                    f = child;
                } else {
                    f = null;
                }
            } else {
                if (create) {
                    f = f.createFile("application/octet-stream", name);
                } else {
                    f = null;
                }
            }
        }

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting file: " + file, e);
        return null;
    }
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getDocument(Context context, File file) {
    try {//from  w w w  . jav a  2s. c o m
        String path = file.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null) {
            return cached;
        }

        String baseFolder = getExtSdCardFolder(context, file);
        if (baseFolder == null) {
            return file.exists() ? DocumentFile.fromFile(file) : null;
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = file.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);
        for (String segment : segments) {
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                return null;
            }
        }

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting document: " + file, e);
        return null;
    }
}

From source file:com.github.chenxiaolong.dualbootpatcher.FileUtils.java

@NonNull
public static DocumentFile getDocumentFile(@NonNull Context context, @NonNull Uri uri) {
    DocumentFile df = null;/*from   www .jav  a2  s  .  c om*/

    if (FILE_SCHEME.equals(uri.getScheme())) {
        df = DocumentFile.fromFile(new File(uri.getPath()));
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && SAF_SCHEME.equals(uri.getScheme())
            && SAF_AUTHORITY.equals(uri.getAuthority())) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            df = DocumentFile.fromSingleUri(context, uri);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && DocumentsContract.isTreeUri(uri)) {
            df = DocumentFile.fromTreeUri(context, uri);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Best guess is that it's a tree...
            df = DocumentFile.fromTreeUri(context, uri);
        }
    }

    if (df == null) {
        throw new IllegalArgumentException("Invalid URI: " + uri);
    }

    return df;
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

/**
 * Starts copy of file//from   w  w  w  .  java  2 s. c o  m
 * Supports : {@link File}, {@link jcifs.smb.SmbFile}, {@link DocumentFile}, {@link CloudStorage}
 * @param lowOnMemory defines whether system is running low on memory, in which case we'll switch to
 *                    using streams instead of channel which maps the who buffer in memory.
 *                    TODO: Use buffers even on low memory but don't map the whole file to memory but
 *                          parts of it, and transfer each part instead.
 */
private void startCopy(boolean lowOnMemory) throws IOException {

    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    BufferedInputStream bufferedInputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    try {

        // initializing the input channels based on file types
        if (mSourceFile.isOtgFile()) {
            // source is in otg
            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentSourceFile = OTGUtil.getDocumentFile(mSourceFile.getPath(), mContext, false);

            bufferedInputStream = new BufferedInputStream(
                    contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSmb()) {

            // source is in smb
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSftp()) {
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isDropBoxFile()) {

            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageDropbox.download(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath())));
        } else if (mSourceFile.isBoxFile()) {

            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageBox.download(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath())));
        } else if (mSourceFile.isGoogleDriveFile()) {

            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageGdrive.download(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath())));
        } else if (mSourceFile.isOneDriveFile()) {

            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
            bufferedInputStream = new BufferedInputStream(cloudStorageOnedrive
                    .download(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath())));
        } else {

            // source file is neither smb nor otg; getting a channel from direct file instead of stream
            File file = new File(mSourceFile.getPath());
            if (FileUtil.isReadable(file)) {

                if (mTargetFile.isOneDriveFile() || mTargetFile.isDropBoxFile()
                        || mTargetFile.isGoogleDriveFile() || mTargetFile.isBoxFile() || lowOnMemory) {
                    // our target is cloud, we need a stream not channel
                    bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                } else {

                    inChannel = new RandomAccessFile(file, "r").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentSourceFile = FileUtil.getDocumentFile(file, mSourceFile.isDirectory(),
                        mContext);

                bufferedInputStream = new BufferedInputStream(
                        contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        // initializing the output channels based on file types
        if (mTargetFile.isOtgFile()) {

            // target in OTG, obtain streams from DocumentFile Uri's

            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentTargetFile = OTGUtil.getDocumentFile(mTargetFile.getPath(), mContext, true);

            bufferedOutputStream = new BufferedOutputStream(
                    contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSftp()) {
            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSmb()) {

            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isDropBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);

            if (mSourceFile.isDropBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageDropbox.copy(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                return;
            }
        } else if (mTargetFile.isBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);

            if (mSourceFile.isBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageBox.copy(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isGoogleDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);

            if (mSourceFile.isGoogleDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageGdrive.copy(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isOneDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);

            if (mSourceFile.isOneDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageOnedrive.copy(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageOnedrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else {
            // copying normal file, target not in OTG
            File file = new File(mTargetFile.getPath());
            if (FileUtil.isWritable(file)) {

                if (lowOnMemory) {
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                } else {

                    outChannel = new RandomAccessFile(file, "rw").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentTargetFile = FileUtil.getDocumentFile(file, mTargetFile.isDirectory(),
                        mContext);

                bufferedOutputStream = new BufferedOutputStream(
                        contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        if (bufferedInputStream != null) {
            if (bufferedOutputStream != null)
                copyFile(bufferedInputStream, bufferedOutputStream);
            else if (outChannel != null) {
                copyFile(bufferedInputStream, outChannel);
            }
        } else if (inChannel != null) {
            if (bufferedOutputStream != null)
                copyFile(inChannel, bufferedOutputStream);
            else if (outChannel != null)
                copyFile(inChannel, outChannel);
        }

    } catch (IOException e) {
        e.printStackTrace();
        Log.d(getClass().getSimpleName(), "I/O Error!");
        throw new IOException();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();

        // we ran out of memory to map the whole channel, let's switch to streams
        AppConfig.toast(mContext, mContext.getString(R.string.copy_low_memory));

        startCopy(true);
    } finally {

        try {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            if (bufferedInputStream != null)
                bufferedInputStream.close();
            if (bufferedOutputStream != null)
                bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            // failure in closing stream
        }

        //If target file is copied onto the device and copy was successful, trigger media store
        //rescan

        if ((mTargetFile.isLocal() || mTargetFile.isOtgFile()) && mTargetFile.exists(mContext)) {

            DocumentFile documentFile = FileUtil.getDocumentFile(mTargetFile.getFile(), false, mContext);
            //If FileUtil.getDocumentFile() returns null, fall back to DocumentFile.fromFile()
            if (documentFile == null)
                documentFile = DocumentFile.fromFile(mTargetFile.getFile());

            FileUtils.scanFile(documentFile.getUri(), mContext);
        }
    }
}

From source file:org.totschnig.myexpenses.util.Utils.java

/**
 * @return the directory user has configured in the settings, if not configured yet
 * returns {@link android.content.ContextWrapper#getExternalFilesDir(String)} with argument null
 *//*from   www  .  j a v a2 s.  com*/
public static DocumentFile getAppDir() {
    String prefString = PrefKey.APP_DIR.getString(null);
    if (prefString != null) {
        Uri pref = Uri.parse(prefString);
        if (pref.getScheme().equals("file")) {
            File appDir = new File(pref.getPath());
            if (appDir.mkdir() || appDir.isDirectory()) {
                return DocumentFile.fromFile(appDir);
            } /* else {
               Utils.reportToAcra(new Exception("Found invalid preference value " + prefString));
              }*/
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //this will return null, if called on a pre-Lolipop device
                DocumentFile documentFile = DocumentFile.fromTreeUri(MyApplication.getInstance(), pref);
                if (dirExistsAndIsWritable(documentFile)) {
                    return documentFile;
                }
            }
        }
    }
    File externalFilesDir = MyApplication.getInstance().getExternalFilesDir(null);
    if (externalFilesDir != null) {
        return DocumentFile.fromFile(externalFilesDir);
    } else {
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        AcraHelper.report(new Exception("getExternalFilesDir returned null; " + permission + " : "
                + ContextCompat.checkSelfPermission(MyApplication.getInstance(), permission)));
        return null;
    }
}

From source file:com.almalence.opencam.SavingService.java

public void saveResultPictureNew(long sessionID) {
    if (ApplicationScreen.getForceFilename() != null) {
        saveResultPicture(sessionID);//from  w  w  w  . jav  a  2 s .  c  om
        return;
    }

    initSavingPrefs();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // save fused result
    try {
        DocumentFile saveDir = getSaveDirNew(false);

        int imagesAmount = Integer
                .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID)));

        if (imagesAmount == 0)
            imagesAmount = 1;

        int imageIndex = 0;
        String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID));
        if (sImageIndex != null)
            imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID)));

        if (imageIndex != 0)
            imagesAmount = 1;

        ContentValues values = null;

        boolean hasDNGResult = false;
        for (int i = 1; i <= imagesAmount; i++) {
            hasDNGResult = false;
            String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));

            if (format != null && format.equalsIgnoreCase("dng"))
                hasDNGResult = true;

            String idx = "";

            if (imagesAmount != 1)
                idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult)
                        ? i - imagesAmount / 2
                        : i);

            String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID));

            // define file name format. from settings!
            String fileFormat = getExportFileName(modeName);
            fileFormat += idx;

            DocumentFile file = null;
            if (ApplicationScreen.getForceFilename() == null) {
                if (hasDNGResult) {
                    file = saveDir.createFile("image/x-adobe-dng", fileFormat + ".dng");
                } else {
                    file = saveDir.createFile("image/jpeg", fileFormat);
                }
            } else {
                file = DocumentFile.fromFile(ApplicationScreen.getForceFilename());
            }

            // Create buffer image to deal with exif tags.
            OutputStream os = null;
            File bufFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg");
            try {
                os = new FileOutputStream(bufFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Take only one result frame from several results
            // Used for PreShot plugin that may decide which result to save
            if (imagesAmount == 1 && imageIndex != 0) {
                i = imageIndex;
                //With changed frame index we have to get appropriate frame format
                format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));
            }

            String resultOrientation = getFromSharedMem(
                    "resultframeorientation" + i + Long.toString(sessionID));
            int orientation = 0;
            if (resultOrientation != null)
                orientation = Integer.parseInt(resultOrientation);

            String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID));
            Boolean cameraMirrored = false;
            if (resultMirrored != null)
                cameraMirrored = Boolean.parseBoolean(resultMirrored);

            int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
            if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) {
                x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
                y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            }

            Boolean writeOrientationTag = true;
            String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID));
            if (writeOrientTag != null)
                writeOrientationTag = Boolean.parseBoolean(writeOrientTag);

            if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format

                if (os != null) {
                    byte[] frame = SwapHeap.SwapFromHeap(
                            Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))),
                            Integer.parseInt(
                                    getFromSharedMem("resultframelen" + i + Long.toString(sessionID))));
                    os.write(frame);
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (format != null && format.equalsIgnoreCase("dng")
                    && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored);
            } else {// if result in nv21 format
                int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID)));
                com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null);
                Rect r;

                String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID));
                if ((null == res) || "".equals(res) || "true".equals(res)) {
                    // to avoid problems with SKIA
                    int cropHeight = out.getHeight() - out.getHeight() % 16;
                    r = new Rect(0, 0, out.getWidth(), cropHeight);
                } else {
                    if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) {
                        // to avoid problems with SKIA
                        int cropHeight = out.getHeight() - out.getHeight() % 16;
                        r = new Rect(0, 0, out.getWidth(), cropHeight);
                    } else {
                        int crop0 = Integer
                                .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID)));
                        int crop1 = Integer
                                .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID)));
                        int crop2 = Integer
                                .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID)));
                        int crop3 = Integer
                                .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID)));

                        r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3);
                    }
                }

                jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95"));
                if (!out.compressToJpeg(r, jpegQuality, os)) {
                    ApplicationScreen.getMessageHandler()
                            .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
                    return;
                }
                SwapHeap.FreeFromHeap(yuv);
            }

            String orientation_tag = String.valueOf(0);
            //            int sensorOrientation = CameraController.getSensorOrientation(CameraController.getCameraIndex());
            //            int displayOrientation = CameraController.getDisplayOrientation();
            ////            sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation
            ////                  : displayOrientation)) % 360;
            //            if (cameraMirrored) displayOrientation = -displayOrientation;
            //            
            //            // Calculate desired JPEG orientation relative to camera orientation to make
            //            // the image upright relative to the device orientation
            //            orientation = (sensorOrientation + displayOrientation + 360) % 360;

            switch (orientation) {
            default:
            case 0:
                orientation_tag = String.valueOf(0);
                break;
            case 90:
                orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90);
                break;
            case 180:
                orientation_tag = String.valueOf(180);
                break;
            case 270:
                orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270);
                break;
            }

            int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            if (writeOrientationTag) {
                switch ((orientation + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            } else {
                switch ((additionalRotationValue + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            }

            if (!enableExifTagOrientation)
                exif_orientation = ExifInterface.ORIENTATION_NORMAL;

            values = new ContentValues();
            values.put(ImageColumns.TITLE,
                    file.getName().substring(0,
                            file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".")
                                    : file.getName().length()));
            values.put(ImageColumns.DISPLAY_NAME, file.getName());
            values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(ImageColumns.MIME_TYPE, "image/jpeg");

            if (enableExifTagOrientation) {
                if (writeOrientationTag) {
                    values.put(ImageColumns.ORIENTATION, String.valueOf(
                            (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360));
                } else {
                    values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360));
                }
            } else {
                values.put(ImageColumns.ORIENTATION, String.valueOf(0));
            }

            String filePath = file.getName();

            // If we able to get File object, than get path from it.
            // fileObject should not be null for files on phone memory.
            File fileObject = Util.getFileFromDocumentFile(file);
            if (fileObject != null) {
                filePath = fileObject.getAbsolutePath();
                values.put(ImageColumns.DATA, filePath);
            } else {
                // This case should typically happen for files saved to SD
                // card.
                String documentPath = Util.getAbsolutePathFromDocumentFile(file);
                values.put(ImageColumns.DATA, documentPath);
            }

            if (!enableExifTagOrientation && !hasDNGResult) {
                Matrix matrix = new Matrix();
                if (writeOrientationTag && (orientation + additionalRotationValue) != 0) {
                    matrix.postRotate((orientation + additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                } else if (!writeOrientationTag && additionalRotationValue != 0) {
                    matrix.postRotate((additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                }
            }

            if (useGeoTaggingPrefExport) {
                Location l = MLocation.getLocation(getApplicationContext());
                if (l != null) {
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
                    if (hasLatLon) {
                        values.put(ImageColumns.LATITUDE, l.getLatitude());
                        values.put(ImageColumns.LONGITUDE, l.getLongitude());
                    }
                }
            }

            File modifiedFile = null;
            if (!hasDNGResult) {
                modifiedFile = saveExifTags(bufFile, sessionID, i, x, y, exif_orientation,
                        useGeoTaggingPrefExport, enableExifTagOrientation);
            }
            if (modifiedFile != null) {
                bufFile.delete();

                if (ApplicationScreen.getForceFilename() == null) {
                    // Copy buffer image with exif tags into result file.
                    InputStream is = null;
                    int len;
                    byte[] buf = new byte[4096];
                    try {
                        os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                        is = new FileInputStream(modifiedFile);
                        while ((len = is.read(buf)) > 0) {
                            os.write(buf, 0, len);
                        }
                        is.close();
                        os.close();
                    } catch (IOException eIO) {
                        eIO.printStackTrace();
                        final IOException eIOFinal = eIO;
                        ApplicationScreen.instance.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MainScreen.getMainContext(),
                                        "Error ocurred:" + eIOFinal.getLocalizedMessage(), Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    copyToForceFileName(modifiedFile);
                }

                modifiedFile.delete();
            } else {
                // Copy buffer image into result file.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                    is = new FileInputStream(bufFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bufFile.delete();
            }

            Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                    values);
            broadcastNewPicture(uri);
        }

        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } catch (IOException e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    }
}

From source file:com.almalence.opencam.SavingService.java

@TargetApi(19)
public static DocumentFile getSaveDirNew(boolean forceSaveToInternalMemory) {
    DocumentFile saveDir = null;/*from w w  w.  j  a  v a  2  s .  co m*/
    boolean usePhoneMem = true;

    String abcDir = "Camera";
    if (sortByData) {
        Calendar rightNow = Calendar.getInstance();
        abcDir = String.format("%tF", rightNow);
    }

    int saveToValue = Integer.parseInt(saveToPreference);
    if (saveToValue == 1 || saveToValue == 2) {
        boolean canWrite = false;
        String uri = saveToPath;
        try {
            saveDir = DocumentFile.fromTreeUri(ApplicationScreen.instance, Uri.parse(uri));
        } catch (Exception e) {
            saveDir = null;
        }
        List<UriPermission> perms = ApplicationScreen.instance.getContentResolver()
                .getPersistedUriPermissions();
        for (UriPermission p : perms) {
            if (p.getUri().toString().equals(uri.toString()) && p.isWritePermission()) {
                canWrite = true;
                break;
            }
        }

        if (saveDir != null && canWrite && saveDir.exists()) {
            if (sortByData) {
                DocumentFile dateFolder = saveDir.findFile(abcDir);
                if (dateFolder == null) {
                    dateFolder = saveDir.createDirectory(abcDir);
                }
                saveDir = dateFolder;
            }
            usePhoneMem = false;
        }
    }

    if (usePhoneMem || forceSaveToInternalMemory) // phone memory (internal
    // sd card)
    {
        saveDir = DocumentFile
                .fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
        DocumentFile abcFolder = saveDir.findFile(abcDir);
        if (abcFolder == null || !abcFolder.exists()) {
            abcFolder = saveDir.createDirectory(abcDir);
        }
        saveDir = abcFolder;
    }

    return saveDir;
}