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.pddstudio.share.Share.java

/**
 * Add a file to the content you want to share.
 * <b>Note:</b> This requires a {@linkplain FileProvider}.
 * @param mimeType - The MIME-Type of the file
 * @param file - The File itself/*w w  w  .  j av  a  2s . c o  m*/
 * @param fileProviderAuthority - The name of your {@linkplain FileProvider}
 * @return -
 */
public Share withFile(String mimeType, File file, String fileProviderAuthority) {
    try {
        Uri fileUri = FileProvider.getUriForFile(activity, fileProviderAuthority, file);
        intentBuilder.setType(mimeType);
        intentBuilder.setStream(fileUri);
        fileAttached = true;
        this.fileUri = fileUri;
    } catch (IllegalArgumentException ex) {
        Log.e("Share",
                "Unable to retrieve Uri for the given file. The given File might be outside the paths supported by the provider.");
        ex.printStackTrace();
    }

    return this;
}

From source file:com.android.browser.UploadHandler.java

private Uri createTempFileContentUri(String suffix) {
    try {/*from w  w w  . j  a  v  a 2 s .c  o  m*/
        File mediaPath = new File(mController.getActivity().getFilesDir(), "captured_media");
        if (!mediaPath.exists() && !mediaPath.mkdir()) {
            throw new RuntimeException("Folder cannot be created.");
        }
        File mediaFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), suffix, mediaPath);
        return FileProvider.getUriForFile(mController.getActivity(), FILE_PROVIDER_AUTHORITY, mediaFile);
    } catch (java.io.IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gnuroot.rsinstaller.RSLauncherMain.java

/**
 * Returns a Uri for the custom tar placed in the project's assets directory.
 * @return//from  w  w  w  . j av a2s  .  c  o m
  */
private Uri getTarUri() {
    File fileHandle = new File(getFilesDir() + "/rs_custom.tar.gz");
    return FileProvider.getUriForFile(this, "com.gnuroot.rsinstaller.fileprovider", fileHandle);
}

From source file:com.android.cts.verifier.managedprovisioning.NfcTestActivity.java

private Uri createUriForImage(String name, String text) {
    final File file = new File(getFilesDir() + File.separator + "images" + File.separator + name);
    file.getParentFile().mkdirs(); //if the folder doesn't exists it is created
    try {//from  www.j av  a2s. c om
        createSampleImage(text).compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
    } catch (FileNotFoundException e) {
        return null;
    }
    return FileProvider.getUriForFile(this, "com.android.cts.verifier.managedprovisioning.fileprovider", file);
}

From source file:com.google.android.apps.forscience.whistlepunk.PictureUtils.java

public static void launchExternalViewer(Activity activity, String fileUrl) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    if (!TextUtils.isEmpty(type)) {
        String filePath = fileUrl;
        if (filePath.startsWith("file:")) {
            filePath = filePath.substring("file:".length());
        }/*from ww  w  . ja va2s . c o  m*/
        Uri photoUri = FileProvider.getUriForFile(activity, activity.getPackageName(), new File(filePath));
        intent.setDataAndType(photoUri, type);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            // Needed to avoid security exception on KitKat.
            intent.setClipData(ClipData.newRawUri(null, photoUri));
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity found to handle this " + fileUrl + " type " + type);
        }
    } else {
        Log.w(TAG, "Could not find mime type for " + fileUrl);
    }
}

From source file:com.hijacker.FeedbackDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    dialogView = getActivity().getLayoutInflater().inflate(R.layout.feedback_dialog, null);

    emailView = (EditText) dialogView.findViewById(R.id.email_et);
    include_report = (CheckBox) dialogView.findViewById(R.id.include_report);
    feedbackView = (EditText) dialogView.findViewById(R.id.feedback_et);
    progress = (ProgressBar) dialogView.findViewById(R.id.progress);

    emailView.setText(pref.getString("user_email", ""));
    emailView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override/* w w  w.j a  v a  2s . co m*/
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                feedbackView.requestFocus();
                return true;
            }
            return false;
        }
    });

    report = null;
    include_report.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked && report == null) {
                progress.setIndeterminate(true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        report = new File(Environment.getExternalStorageDirectory() + "/report.txt");
                        if (!createReport(report, path, null, Shell.getFreeShell().getShell())) {
                            if (debug)
                                Log.e("HIJACKER/feedbackDialog", "Report not generated");
                            report = null;
                        }
                        runInHandler(new Runnable() {
                            @Override
                            public void run() {
                                progress.setIndeterminate(false);
                            }
                        });
                    }
                }).start();
            }
        }
    });

    builder.setView(dialogView);
    builder.setTitle(getString(R.string.feedback));
    builder.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    builder.setNeutralButton(R.string.send_email, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/text");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "kiriakopoulos44@gmail.com" });
            intent.putExtra(Intent.EXTRA_SUBJECT, "Hijacker feedback");
            if (report != null) {
                Uri attachment = FileProvider.getUriForFile(
                        FeedbackDialog.this.getActivity().getApplicationContext(),
                        BuildConfig.APPLICATION_ID + ".provider", report);
                intent.putExtra(Intent.EXTRA_STREAM, attachment);
            }
            intent.putExtra(Intent.EXTRA_TEXT, feedbackView.getText().toString());
            startActivity(intent);
        }
    });
    return builder.create();
}

From source file:org.amahi.anywhere.util.Downloader.java

private void finishDownloading() {
    DownloadManager.Query downloadQuery = new DownloadManager.Query().setFilterById(downloadId);

    Cursor downloadInformation = getDownloadManager(context).query(downloadQuery);

    downloadInformation.moveToFirst();/*from  w  w w  .  ja  va2  s .  co m*/

    int downloadStatus = downloadInformation
            .getInt(downloadInformation.getColumnIndex(DownloadManager.COLUMN_STATUS));

    if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
        String downloadUri = downloadInformation
                .getString(downloadInformation.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

        if (downloadUri.substring(0, 7).matches("file://")) {
            downloadUri = downloadUri.substring(7);
        }

        try {
            URI uri = new URI(downloadUri);
            downloadUri = uri.getPath();
        } catch (URISyntaxException e) {
            Log.e("Downloader", "Invalid Uri: " + downloadUri);
        }

        File file = new File(downloadUri);
        Uri contentUri = FileProvider.getUriForFile(context, "org.amahi.anywhere.fileprovider", file);
        BusProvider.getBus().post(new FileDownloadedEvent(contentUri));
    } else {
        BusProvider.getBus().post(new FileDownloadFailedEvent());
    }

    downloadInformation.close();

}

From source file:com.owncloud.android.ui.helpers.FilesUploadHelper.java

/**
 * Function to send an intent to the device's camera to capture a picture
 * *//*from   w  ww.  j  a  v  a  2  s  .  c  o m*/
public void uploadFromCamera(final int requestCode) {
    Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = createImageFile();
    if (photoFile != null) {
        Uri photoUri = FileProvider.getUriForFile(activity.getApplicationContext(),
                activity.getResources().getString(R.string.file_provider_authority), photoFile);
        pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    }
    if (pictureIntent.resolveActivity(activity.getPackageManager()) != null) {
        activity.startActivityForResult(pictureIntent, requestCode);
    }
}

From source file:com.dexin.MainActivity.java

public void startCamera() {
    if (PermissionUtils.requestPermission(this, CAMERA_PERMISSIONS_REQUEST,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider",
                getCameraFile());/*  ww  w  .  j  a  va2  s. co  m*/
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CAMERA_IMAGE_REQUEST);
    }
}

From source file:com.android.ted.gank.main.ViewerFragment.java

private void checkFileAndSetWallPaper(File file) {
    if (null != file && file.exists()) {
        //get the contentUri for this file and start the intent
        Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.android.ted.gank.fileprovider", file);
        //get crop intent
        Intent intent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(contentUri);
        //start activity for result so we can animate if we finish
        getActivity().startActivityForResult(intent, ViewerActivity.REQUEST_CODE_SET_WALLPAPER);
    }/*from  w  w  w . java2s  .co  m*/
}