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

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

Introduction

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

Prototype

public abstract String getType();

Source Link

Usage

From source file:com.pavlospt.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;/*from   w w  w .  jav a2s .  c  o m*/
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    logDebug("External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    logDebug("From Google Drive guessed type: " + getMimeType(fileName));

    logDebug("Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    logDebug("Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}

From source file:com.xxxifan.devbox.library.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;//from  w w  w  .j av  a 2 s . c o m
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    Log.e(TAG, "External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    Log.e(TAG, "From Drive guessed type: " + getMimeType(fileName));

    Log.e(TAG, "Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    Log.e(TAG, "Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}

From source file:com.pavlospt.rxfile.RxFile.java

private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data,
        final int requiredWidth, final int requiredHeight, final int kind) {
    return Observable.fromCallable(new Func0<Bitmap>() {
        @Override/*from www  .j a va 2 s.c o m*/
        public Bitmap call() {
            Bitmap bitmap = null;
            ParcelFileDescriptor parcelFileDescriptor;
            final BitmapFactory.Options options = new BitmapFactory.Options();
            if (requiredWidth > 0 && requiredHeight > 0) {
                options.inJustDecodeBounds = true;
                options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
                options.inJustDecodeBounds = false;
            }
            if (!isMediaUri(data)) {
                logDebug("Not a media uri:" + data);
                if (isGoogleDriveDocument(data)) {
                    logDebug("Google Drive Uri:" + data);
                    DocumentFile file = DocumentFile.fromSingleUri(context, data);
                    if (file.getType().startsWith(Constants.IMAGE_TYPE)
                            || file.getType().startsWith(Constants.VIDEO_TYPE)) {
                        logDebug("Google Drive Uri:" + data + " (Video or Image)");
                        try {
                            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                    Constants.READ_MODE);
                            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                            bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                            parcelFileDescriptor.close();
                            return bitmap;
                        } catch (IOException e) {
                            logError("Exception:" + e.getMessage() + " line: 209");
                            e.printStackTrace();
                        }
                    }
                } else if (data.getScheme().equals(Constants.FILE)) {
                    logDebug("Dropbox or other DocumentsProvider Uri:" + data);
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 223");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 235");
                        e.printStackTrace();
                    }
                }
            } else {
                logDebug("Uri for thumbnail:" + data);
                String[] parts = data.getLastPathSegment().split(":");
                String fileId = parts[1];
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver().query(data, null, null, null, null);
                    if (cursor != null) {
                        logDebug("Cursor size:" + cursor.getCount());
                        if (cursor.moveToFirst()) {
                            if (data.toString().contains(Constants.VIDEO)) {
                                bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            } else if (data.toString().contains(Constants.IMAGE)) {
                                bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            }
                        }
                    }
                    return bitmap;
                } catch (Exception e) {
                    logError("Exception:" + e.getMessage() + " line: 266");
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            }
            return bitmap;
        }
    });
}

From source file:com.xxxifan.devbox.library.rxfile.RxFile.java

private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data,
        final int requiredWidth, final int requiredHeight, final int kind) {
    return Observable.fromCallable(new Func0<Bitmap>() {
        @Override//from   ww  w . j a  va  2 s. c  o  m
        public Bitmap call() {
            Bitmap bitmap = null;
            ParcelFileDescriptor parcelFileDescriptor;
            final BitmapFactory.Options options = new BitmapFactory.Options();
            if (requiredWidth > 0 && requiredHeight > 0) {
                options.inJustDecodeBounds = true;
                options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
                options.inJustDecodeBounds = false;
            }
            if (!isMediaUri(data)) {
                Log.e(TAG, "Not a media uri");
                if (isGoogleDriveDocument(data)) {
                    Log.e(TAG, "Google Drive Uri");
                    DocumentFile file = DocumentFile.fromSingleUri(context, data);
                    if (file.getType().startsWith(Constants.IMAGE_TYPE)
                            || file.getType().startsWith(Constants.VIDEO_TYPE)) {
                        Log.e(TAG, "Google Drive Uri");
                        try {
                            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                    Constants.READ_MODE);
                            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                            bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                            parcelFileDescriptor.close();
                            return bitmap;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else if (data.getScheme().equals(Constants.FILE)) {
                    Log.e(TAG, "Dropbox or other content provider");
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                Log.e(TAG, "Uri for thumbnail: " + data.toString());
                Log.e(TAG, "Uri for thumbnail: " + data);
                String[] parts = data.getLastPathSegment().split(":");
                String fileId = parts[1];
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver().query(data, null, null, null, null);
                    if (cursor != null) {
                        Log.e(TAG, "Cursor size: " + cursor.getCount());
                        if (cursor.moveToFirst()) {
                            if (data.toString().contains(Constants.VIDEO)) {
                                bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            } else if (data.toString().contains(Constants.IMAGE)) {
                                Log.e(TAG, "Image Uri");
                                bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            }
                            Log.e(TAG, bitmap == null ? "null" : "not null");
                        }
                    }
                    return bitmap;
                } catch (Exception e) {
                    Log.e(TAG, "Exception while getting thumbnail:" + e.getMessage());
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            }
            return bitmap;
        }
    });
}

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

/**
 * Open file from OTG//from  w w w  .  j ava 2 s . c o  m
 */
public static void openunknown(DocumentFile f, Context c, boolean forcechooser, boolean useNewStack) {
    Intent chooserIntent = new Intent();
    chooserIntent.setAction(Intent.ACTION_VIEW);
    chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        chooserIntent.setDataAndType(f.getUri(), type);
        Intent activityIntent;
        if (forcechooser) {
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
            activityIntent = Intent.createChooser(chooserIntent, c.getString(R.string.openwith));
        } else {
            activityIntent = chooserIntent;
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
        }

        try {
            c.startActivity(activityIntent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c, useNewStack);
        }
    } else {
        openWith(f, c, useNewStack);
    }
}

From source file:com.osama.cryptofm.filemanager.listview.FileSelectionManagement.java

void openFile(final String filename) {
    if (SharedData.IS_IN_COPY_MODE) {
        return;/*www. j ava  2  s  . com*/
    }
    if (FileUtils.getExtension(filename).equals("pgp")) {
        Log.d(TAG, "openFile: File name is: " + filename);
        if (SharedData.KEY_PASSWORD == null) {
            final Dialog dialog = new Dialog(mContext);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.password_dialog_layout);
            dialog.show();
            dialog.findViewById(R.id.cancel_decrypt_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            final EditText editText = (EditText) dialog.findViewById(R.id.key_password);
            dialog.findViewById(R.id.decrypt_file_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editText.getText().length() < 1) {
                        editText.setError("please give me your encryption password");
                        return;
                    } else {
                        SharedData.KEY_PASSWORD = editText.getText().toString();
                        dialog.dismiss();
                        new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD,
                                SharedData.USERNAME, FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD)
                                        .execute();
                    }

                }
            });
        } else {
            new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD, SharedData.USERNAME,
                    FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD).execute();
        }

    } else {
        //open file
        if (SharedData.EXTERNAL_SDCARD_ROOT_PATH != null
                && FileUtils.CURRENT_PATH.contains(SharedData.EXTERNAL_SDCARD_ROOT_PATH)) {
            //open the document file
            DocumentFile file = FileDocumentUtils.getDocumentFile(FileUtils.getFile(filename));
            Intent intent = new Intent();
            intent.setDataAndType(file.getUri(), file.getType());
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with");
            mContext.startActivity(x);
            return;
        }
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getExtension(filename));

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uri = FileProvider.getUriForFile(mContext,
                    mContext.getApplicationContext().getPackageName() + ".provider",
                    FileUtils.getFile(filename));
            intent.setDataAndType(uri, mimeType);
        } else {
            intent.setDataAndType(Uri.fromFile(FileUtils.getFile(filename)), mimeType);
        }
        intent.setAction(Intent.ACTION_VIEW);
        Intent x = Intent.createChooser(intent, "Open with: ");
        mContext.startActivity(x);
    }
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openunknown(DocumentFile f, Context c, boolean forcechooser) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        intent.setDataAndType(f.getUri(), type);
        Intent startintent;/*  w ww.  ja  v a  2s. com*/
        if (forcechooser)
            startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else
            startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}

From source file:com.osama.cryptofm.tasks.MoveTask.java

private void moveDocumentFile(DocumentFile file) throws Exception {
    if (file.isDirectory()) {
        Log.d(TAG, "moveDocumentFile: Yes document file is directory");
        //change the destination folder
        mDestinationFolder = mDestinationFolder + file.getName() + "/";
        //check if destination folder is not document file
        if (FileUtils.isDocumentFile(mDestinationFolder)) {
            rootDocumentFile = rootDocumentFile.createDirectory(file.getName());
        } else {//from ww w  . j  a  v  a2s . c  om
            File tmp = new File(mDestinationFolder);
            if (!tmp.exists()) {
                tmp.mkdir();
            } else {
                return;
            }
        }
        for (DocumentFile f : file.listFiles()) {
            moveDocumentFile(f);
        }
    } else {
        isNextFile = true;
        publishProgress(file.getName());
        publishProgress("" + 0);
        //check if pasting in internal storage
        if (!FileUtils.isDocumentFile(mDestinationFolder)) {
            Log.d(TAG, "moveDocumentFile: moving document file in internal storage");
            File destinationFile = new File(mDestinationFolder + file.getName());
            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    new BufferedOutputStream(new FileOutputStream(destinationFile)), file.length());
        } else {
            Log.d(TAG, "moveDocumentFile: Moving document file honey");
            DocumentFile destFile = rootDocumentFile.createFile(file.getType(), file.getName());

            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    CryptoFM.getContext().getContentResolver().openOutputStream(destFile.getUri()),
                    file.length());
        }
    }

    //delete the input file
    //if copying then don't
    if (SharedData.IS_COPYING_NOT_MOVING) {
        return;
    }
    if (!file.delete()) {
        throw new IOException("cannot move files");
    }
}