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.emojify.MainActivity.java

/**
 * Creates a temporary image file and captures a picture to store in it.
 *//*w  ww .j av a  2 s . c  o m*/
private void launchCamera() {

    // Create the capture image intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the temporary File where the photo should go
        File photoFile = null;
        try {
            photoFile = BitmapUtils.createTempImageFile(this);
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {

            // Get the path of the temporary file
            mTempPhotoPath = photoFile.getAbsolutePath();

            // Get the content URI for the image file
            Uri photoURI = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);

            // Add the URI so the camera can store the image
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            // Launch the camera activity
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

From source file:com.mediatek.mms.util.VCardUtils.java

public static void importVCard(Context context, FileAttachmentModel attach) {
    MessageUtils.deleteAllSharedFiles(context, ".vcf");
    MmsLog.d(TAG, "importVCard, file uri: " + attach.getUri());
    final File tempVCard = MessageUtils.createTempFileExposed(context, attach.getUri(), attach.getSrc());
    if (tempVCard == null || !tempVCard.exists() || tempVCard.length() <= 0) {
        MmsLog.e(TAG, "importVCard, file is not exists or empty " + tempVCard);
        return;//from ww  w . j  a  v  a 2 s  .c o m
    }

    Uri vCardUri = FileProvider.getUriForFile(context, MMS_FILE_PROVIDER_AUTHORITIES, tempVCard);
    MmsLog.i(TAG, "importVCard, vCard uri: " + vCardUri);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(vCardUri, attach.getContentType().toLowerCase());
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
}

From source file:de.grundid.plusrad.map.ShowMap.java

public void performExport(String geoJsonData) {
    try {/*from  w w  w.j  av a 2s. c o  m*/
        File exportFile = createTrackFile(geoJsonData);
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        Uri shareUri = FileProvider.getUriForFile(this, "de.grundid.plusrad.fileprovider", exportFile);
        shareIntent.setData(shareUri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, shareUri);
        shareIntent.setType("text/comma_separated_values/csv");
        shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "Track exportieren"));
    } catch (IOException e) {
        e.printStackTrace();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Fehler").setMessage("Fehler beim Exportieren des Tracks. [" + e.getMessage() + "]");
        builder.setPositiveButton("OK", null).show();
    }
}

From source file:com.microsoft.projectoxford.visionsample.helper.SelectImageActivity.java

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        // Save the photo taken to a temporary file.
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {//  ww  w  .  j a  va2 s  . c  o m
            mFilePhotoTaken = File.createTempFile("IMG_", /* prefix */
                    ".jpg", /* suffix */
                    storageDir /* directory */
            );

            // Create the File where the photo should go
            // Continue only if the File was successfully created
            if (mFilePhotoTaken != null) {
                mUriPhotoTaken = FileProvider.getUriForFile(this,
                        "com.microsoft.projectoxford.visionsample.fileprovider", mFilePhotoTaken);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);

                // Finally start camera activity
                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
            }
        } catch (IOException e) {
            setInfo(e.getMessage());
        }
    }
}

From source file:com.jaspersoft.android.jaspermobile.activities.share.AnnotationActivity.java

@OptionsItem(R.id.annotationDoneAction)
void annotationDoneAction() {
    ScreenCapture reportScreenCapture = ScreenCapture.Factory.capture(container);
    mSaveScreenCaptureCase.execute(reportScreenCapture, new SimpleSubscriber<File>() {
        @Override/*  ww  w. j  a va 2s.c o m*/
        public void onStart() {
            ProgressDialogFragment.builder(getSupportFragmentManager()).setLoadingMessage(R.string.loading_msg)
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            finish();
                        }
                    }).show();
        }

        @Override
        public void onError(Throwable e) {
            mRequestExceptionHandler.showCommonErrorMessage(e);
        }

        @Override
        public void onNext(File item) {
            Uri sharedFileUri = FileProvider.getUriForFile(AnnotationActivity.this, CACHE_AUTHORITY, item);

            ShareCompat.IntentBuilder.from(AnnotationActivity.this).setType("image/*").setStream(sharedFileUri)
                    .setSubject(getString(R.string.share_message)).setChooserTitle(R.string.share_chooser_title)
                    .startChooser();
        }

        @Override
        public void onCompleted() {
            ProgressDialogFragment.dismiss(getSupportFragmentManager());
            analytics.sendEvent(Analytics.EventCategory.RESOURCE.getValue(),
                    Analytics.EventAction.SHARED.getValue(), null);
        }
    });
}

From source file:fr.free.nrw.commons.settings.SettingsFragment.java

private void sendAppLogsViaEmail() {
    String appLogs = Utils.getAppLogs();
    File appLogsFile = FileUtils.createAndGetAppLogsFile(appLogs);

    Context applicationContext = getActivity().getApplicationContext();
    Uri appLogsFilePath = FileProvider.getUriForFile(getActivity(),
            applicationContext.getPackageName() + ".provider", appLogsFile);

    Intent feedbackIntent = new Intent(Intent.ACTION_SEND);
    feedbackIntent.setType("message/rfc822");
    feedbackIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { CommonsApplication.LOGS_PRIVATE_EMAIL });
    feedbackIntent.putExtra(Intent.EXTRA_SUBJECT,
            String.format(CommonsApplication.FEEDBACK_EMAIL_SUBJECT, BuildConfig.VERSION_NAME));
    feedbackIntent.putExtra(Intent.EXTRA_STREAM, appLogsFilePath);

    try {//from  w  w w  .  j av  a2s  .  com
        startActivity(feedbackIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(getActivity(), R.string.no_email_client, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.callrecorder.android.FileHelper.java

public static Uri getContentUri(Context context, Uri uri) {
    if (uri.getScheme() == "content")
        return uri;
    return FileProvider.getUriForFile(context, "com.callrecorder.android.fileprovider",
            new File(uri.getPath()));
}

From source file:org.eyeseetea.malariacare.fragments.AVFragment.java

@Override
public void OpenMedia(String resourcePath) {
    Intent implicitIntent = new Intent();
    implicitIntent.setAction(Intent.ACTION_VIEW);
    File file = new File(resourcePath);
    Uri contentUri = FileProvider.getUriForFile(getActivity(),
            BuildConfig.APPLICATION_ID + ".layout.adapters.dashboard.AVAdapter", file);

    implicitIntent.setDataAndType(contentUri,
            PreferencesState.getInstance().getContext().getContentResolver().getType(contentUri));
    implicitIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    implicitIntent.putExtra(Intent.EXTRA_STREAM, contentUri);

    if (isThereAnAppThatCanHandleThis(implicitIntent, getActivity())) {
        getActivity().startActivity(Intent.createChooser(implicitIntent,
                PreferencesState.getInstance().getContext().getString(R.string.feedback_view_image)));
    } else {/* w  w  w .ja v a 2  s  .  c  o m*/
        showToast(R.string.error_unable_to_find_app_than_can_open_file, getActivity());
    }
}

From source file:com.seongil.avatarpicker.AbstractAvatarPicker.java

private void createTempFile() {
    final File directory = getDirectoryFile();
    final String timeStamp = new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.KOREA).format(new Date());
    try {/*from   w w  w  . ja v  a2s.  c  o  m*/
        File tempFile = File.createTempFile(timeStamp, ".jpeg", directory);
        mUri = FileProvider.getUriForFile(getContext(), getFileProviderAuthorities(), tempFile);
    } catch (IllegalArgumentException | IOException e) {
        showToastMsg(e.getMessage());
    }
}

From source file:com.ichi2.anki.multimediacard.fields.BasicImageFieldController.java

@Override
public void createUI(Context context, LinearLayout layout) {
    mImagePreview = new ImageView(mActivity);

    DisplayMetrics metrics = getDisplayMetrics();

    int height = metrics.heightPixels;
    int width = metrics.widthPixels;

    LinearLayout.LayoutParams p = new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    setPreviewImage(mField.getImagePath(), getMaxImageSize());
    mImagePreview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    mImagePreview.setAdjustViewBounds(true);

    mImagePreview.setMaxHeight((int) Math.round(height * 0.4));
    mImagePreview.setMaxWidth((int) Math.round(width * 0.6));

    mBtnGallery = new Button(mActivity);
    mBtnGallery.setText(gtxt(R.string.multimedia_editor_image_field_editing_galery));
    mBtnGallery.setOnClickListener(new View.OnClickListener() {
        @Override//  w w  w  . ja va  2  s .  c o  m
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            mActivity.startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
        }
    });

    mBtnCamera = new Button(mActivity);
    mBtnCamera.setText(gtxt(R.string.multimedia_editor_image_field_editing_photo));
    mBtnCamera.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("NewApi")
        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            File image;
            File storageDir;
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date());
            try {
                storageDir = mActivity.getCacheDir();
                image = File.createTempFile("img_" + timeStamp, ".jpg", storageDir);
                mTempCameraImagePath = image.getPath();
                Uri uriSavedImage = FileProvider.getUriForFile(mActivity,
                        mActivity.getApplicationContext().getPackageName() + ".apkgfileprovider", image);

                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
                mActivity.startActivityForResult(cameraIntent, ACTIVITY_TAKE_PICTURE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    // Chromebooks do not support camera capture yet.
    if (CompatHelper.isChromebook()) {
        mBtnCamera.setVisibility(View.INVISIBLE);
    }

    layout.addView(mImagePreview, android.view.ViewGroup.LayoutParams.FILL_PARENT, p);
    layout.addView(mBtnGallery, android.view.ViewGroup.LayoutParams.FILL_PARENT);
    layout.addView(mBtnCamera, android.view.ViewGroup.LayoutParams.FILL_PARENT);
}