Example usage for android.support.v4.content FileProvider getUriForFile

List of usage examples for android.support.v4.content FileProvider getUriForFile

Introduction

In this page you can find the example usage for android.support.v4.content FileProvider getUriForFile.

Prototype

public static Uri getUriForFile(Context context, String str, File file) 

Source Link

Usage

From source file:com.example.android.dragsource.DragSourceFragment.java

/**
 * Copy a drawable resource into local storage and makes it available via the
 * {@link FileProvider}./*from  w  ww. j a  v  a  2  s.  c  om*/
 *
 * @see Context#getFilesDir()
 * @see FileProvider
 * @see FileProvider#getUriForFile(Context, String, File)
 */
private Uri getFileUri(int sourceResourceId, String targetName) {
    // Create the images/ sub directory if it does not exist yet.
    File filePath = new File(getContext().getFilesDir(), "images");
    if (!filePath.exists() && !filePath.mkdir()) {
        return null;
    }

    // Copy a drawable from resources to the internal directory.
    File newFile = new File(filePath, targetName);
    if (!newFile.exists()) {
        copyImageResourceToFile(sourceResourceId, newFile);
    }

    // Make the file accessible via the FileProvider and retrieve its URI.
    return FileProvider.getUriForFile(getContext(), CONTENT_AUTHORITY, newFile);
}

From source file:com.duy.pascal.ui.file.FileExplorerAction.java

private void shareFile() {
    if (mCheckedList.isEmpty() || mShareActionProvider == null)
        return;/*from  w w  w .  java 2  s  .c  om*/
    try {
        Intent shareIntent = new Intent();
        if (mCheckedList.size() == 1) {
            File file = new File(mCheckedList.get(0).getPath());
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType(MimeTypes.getInstance().getMimeType(file.getPath()));

            Uri fileUri;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider",
                        file);
            } else {
                fileUri = Uri.fromFile(file);
            }
            shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);

            ArrayList<Uri> streams = new ArrayList<>();
            for (File file : mCheckedList) {
                File File = new File(file.getPath());
                Uri fileUri;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    fileUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider",
                            File);
                } else {
                    fileUri = Uri.fromFile(File);
                }
                streams.add(fileUri);
            }

            shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, streams);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        mShareActionProvider.setShareIntent(shareIntent);
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
}

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

void openFile(final String filename) {
    if (SharedData.IS_IN_COPY_MODE) {
        return;//from  w  w  w . j a  v a  2s  .  c o m
    }
    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.my.seams_carv.StartActivity.java

private void dispatchTakePhotoIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (intent.resolveActivity(getPackageManager()) != null) {
        File file = null;/*  ww w.j  av  a  2s .  co m*/
        try {
            file = createImageFile();
        } catch (IOException ex) {
            // DO NOTHING.
            Log.d("xyz", ex.getMessage());
        }

        // Continue only if the File was successfully created.
        if (file != null) {
            // Save the path.
            mPhotoPath = Uri.fromFile(file);

            Log.d("xyz", String.format("Saved file=%s", file.getAbsolutePath()));

            // Specify the authorities under which this content provider can
            // be found. Multiple authorities may be supplied by separating
            // them with a semicolon. Authority names should use a Java-style
            // naming convention (such as com.google.provider.MyProvider) in
            // order to avoid conflicts. Typically this name is the same as
            // the class implementation describing the provider's data
            // structure.
            final String authority = getResources().getString(R.string.file_provider_authority);
            final Uri uri = FileProvider.getUriForFile(this, authority, file);
            Log.d("xyz", String.format("Generated uri=%s", uri));

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(intent, REQ_TAKE_PHOTO);
        }
    }
}

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

@Override
protected void onPostExecute(String s) {
    SharedData.CURRENT_RUNNING_OPERATIONS.clear();

    if (singleFileMode) {
        if (s.equals(DECRYPTION_SUCCESS_MESSAGE)) {
            singleModeDialog.dismiss();//ww  w  .ja v  a2  s.c  om
            Log.d(TAG, "onPostExecute: destination filename is: " + destFilename);
            //open file
            String mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(FileUtils.getExtension(destFilename));

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

                Uri uri = null;
                try {
                    uri = FileProvider.getUriForFile(mContext,
                            mContext.getApplicationContext().getPackageName() + ".provider",
                            TasksFileUtils.getFile(destFilename));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                intent.setDataAndType(uri, mimeType);
            } else {
                try {
                    intent.setDataAndType(Uri.fromFile(TasksFileUtils.getFile(destFilename)), mimeType);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with: ");
            mContext.startActivity(x);
        } else {
            singleModeDialog.dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        }
    } else {
        mProgressDialog.dismiss("Decryption completed");
        SharedData.CURRENT_RUNNING_OPERATIONS.clear();
        Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        UiUtils.reloadData(mContext, mAdapter);
    }

}

From source file:com.luke.lukef.lukeapp.fragments.NewSubmissionFragment.java

/**
 * Activates camera intent/*w  ww  .  j a v  a  2s.  c  om*/
 */
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getMainActivity().getPackageManager()) != null) {
        // Create the File where the photo should go
        if (photoFile != null) {
            this.photoPath = photoFile.getAbsolutePath();
            // Continue only if the File was successfully created
            Uri photoURI = FileProvider.getUriForFile(getMainActivity(), "com.luke.lukef.lukeapp", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            createImageFile();
            dispatchTakePictureIntent();
        }
    }
}

From source file:io.realm.scanner.MainActivity.java

private void dispatchTakePicture() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;//from  ww w  . j a  v  a 2  s .co  m
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile != null) {
            currentPhotoPath = photoFile.getAbsolutePath();
            Uri photoURI = FileProvider.getUriForFile(this, "io.realm.scanner.fileprovider", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

From source file:com.google.android.apps.location.gps.gnsslogger.FileLogger.java

/**
 * Send the current log via email or other options selected from a pop menu shown to the user. A
 * new log is started when calling this function.
 *//*  w  w w.java 2s . c om*/
public void send() {
    if (mFile == null) {
        return;
    }

    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setType("*/*");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "SensorLog");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "");
    // attach the file
    Uri fileURI = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", mFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, fileURI);
    getUiComponent().startActivity(Intent.createChooser(emailIntent, "Send log.."));
    if (mFileWriter != null) {
        try {
            mFileWriter.flush();
            mFileWriter.close();
            mFileWriter = null;
        } catch (IOException e) {
            logException("Unable to close all file streams.", e);
            return;
        }
    }
}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private void sendIntent(File contentFile, String action, String version, String required, String sig) {
    Intent i = new Intent();
    i.setAction(action);/*from  ww w  . j  av  a 2 s  .  c  o  m*/
    Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
            "libcore.tzdata.update_test_app.fileprovider", contentFile);
    i.setData(contentUri);
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.putExtra(EXTRA_VERSION_NUMBER, version);
    i.putExtra(EXTRA_REQUIRED_HASH, required);
    i.putExtra(EXTRA_SIGNATURE, sig);
    sendBroadcast(i);
}

From source file:com.demo.firebase.MainActivity.java

@AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
    Log.d(TAG, "launchCamera");

    // Check that we have permission to read images from external storage.
    String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    if (!EasyPermissions.hasPermissions(this, perm)) {
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage), RC_STORAGE_PERMS, perm);
        return;/*from w  ww .j  a  va 2s.  c  o m*/
    }

    // Choose file storage location, must be listed in res/xml/file_paths.xml
    File dir = new File(Environment.getExternalStorageDirectory() + "/photos");
    File file = new File(dir, UUID.randomUUID().toString() + ".jpg");
    try {
        // Create directory if it does not exist.
        if (!dir.exists()) {
            dir.mkdir();
        }
        boolean created = file.createNewFile();
        Log.d(TAG, "file.createNewFile:" + file.getAbsolutePath() + ":" + created);
    } catch (IOException e) {
        Log.e(TAG, "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
    }

    // Create content:// URI for file, required since Android N
    // See: https://developer.android.com/reference/android/support/v4/content/FileProvider.html
    mFileUri = FileProvider.getUriForFile(this, "com.google.firebase.quickstart.firebasestorage.fileprovider",
            file);

    // Create and launch the intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

    // Grant permission to camera (this is required on KitKat and below)
    List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(takePictureIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, mFileUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    // Start picture-taking intent
    startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}