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.commonsware.cwac.cam2.playground.VideoFragment.java

private void takePicture() {
    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
    VideoRecorderActivity.IntentBuilder b = new VideoRecorderActivity.IntentBuilder(getActivity());
    File f = new File(getActivity().getExternalFilesDir(null), "test.mp4");

    b.to(f);//from  w w w  .j  av  a2 s. c o  m
    ((Contract) getActivity()).setOutput(FileProvider.getUriForFile(getActivity(), AUTHORITY, f));

    if (prefs.getBoolean("highQuality", false)) {
        b.quality(AbstractCameraActivity.Quality.HIGH);
    } else {
        b.quality(AbstractCameraActivity.Quality.LOW);
    }

    if (prefs.getBoolean("ffc", false)) {
        b.facing(Facing.FRONT);
    } else {
        b.facing(Facing.BACK);
    }

    if (prefs.getBoolean("exact_match", false)) {
        b.facingExactMatch();
    }

    if (prefs.getBoolean("debug", false)) {
        b.debug();
    }

    if (prefs.getBoolean("updateMediaStore", false)) {
        b.updateMediaStore();
    }

    /*
        if (prefs.getBoolean("forceClassic", false)) {
          b.forceClassic();
        }
    */

    String durationLimit = prefs.getString("durationLimit", null);

    if (durationLimit != null) {
        b.durationLimit(Integer.parseInt(durationLimit));
    }

    String sizeLimit = prefs.getString("sizeLimit", null);

    if (sizeLimit != null) {
        b.sizeLimit(Integer.parseInt(sizeLimit));
    }

    if (prefs.getBoolean("mirrorPreview", false)) {
        b.mirrorPreview();
    }

    int rawFocusMode = Integer.valueOf(prefs.getString("focusMode", "-1"));

    switch (rawFocusMode) {
    case 0:
        b.focusMode(FocusMode.CONTINUOUS);
        break;
    case 1:
        b.focusMode(FocusMode.OFF);
        break;
    case 2:
        b.focusMode(FocusMode.EDOF);
        break;
    case 3:
        b.focusMode(FocusMode.MACRO);
        break;
    }

    int rawOrientationLock = Integer.valueOf(prefs.getString("olockMode", "0"));

    switch (rawOrientationLock) {
    case 1:
        b.orientationLockMode(OrientationLockMode.PORTRAIT);
        break;
    case 2:
        b.orientationLockMode(OrientationLockMode.LANDSCAPE);
        break;
    }

    int rawChronoType = Integer.valueOf(prefs.getString("chronoType", "-1"));

    switch (rawChronoType) {
    case 0:
        b.chronoType(ChronoType.NONE);
        break;
    case 1:
        b.chronoType(ChronoType.COUNT_DOWN);
        break;
    case 2:
        b.chronoType(ChronoType.COUNT_UP);
        break;
    }

    int rawZoomStyle = Integer.valueOf(prefs.getString("zoomStyle", "0"));

    switch (rawZoomStyle) {
    case 1:
        b.zoomStyle(ZoomStyle.PINCH);
        break;

    case 2:
        b.zoomStyle(ZoomStyle.SEEKBAR);
        break;
    }

    b.onError(new ErrorResultReceiver());

    if (prefs.getBoolean("requestPermissions", true)) {
        b.requestPermissions();
    }

    if (prefs.getBoolean("showRuleOfThirds", false)) {
        b.showRuleOfThirdsGrid();
    }

    Intent result;

    if (prefs.getBoolean("useChooser", false)) {
        result = b.buildChooser("Choose a picture-taking thingy");
    } else {
        result = b.build();
    }

    ((Contract) getActivity()).takeVideo(result);
}

From source file:com.example.android.commitcontent.app.ImageKeyboard.java

private void doCommitContent(@NonNull String description, @NonNull String mimeType, @NonNull File file) {
    final EditorInfo editorInfo = getCurrentInputEditorInfo();

    // Validate packageName again just in case.
    if (!validatePackageName(editorInfo)) {
        return;/*from www . j ava  2s.c o  m*/
    }

    final Uri contentUri = FileProvider.getUriForFile(this, AUTHORITY, file);

    // As you as an IME author are most likely to have to implement your own content provider
    // to support CommitContent API, it is important to have a clear spec about what
    // applications are going to be allowed to access the content that your are going to share.
    final int flag;
    if (Build.VERSION.SDK_INT >= 25) {
        // On API 25 and later devices, as an analogy of Intent.FLAG_GRANT_READ_URI_PERMISSION,
        // you can specify InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION to give
        // a temporary read access to the recipient application without exporting your content
        // provider.
        flag = InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION;
    } else {
        // On API 24 and prior devices, we cannot rely on
        // InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION. You as an IME author
        // need to decide what access control is needed (or not needed) for content URIs that
        // you are going to expose. This sample uses Context.grantUriPermission(), but you can
        // implement your own mechanism that satisfies your own requirements.
        flag = 0;
        try {
            // TODO: Use revokeUriPermission to revoke as needed.
            grantUriPermission(editorInfo.packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } catch (Exception e) {
            Log.e(TAG, "grantUriPermission failed packageName=" + editorInfo.packageName + " contentUri="
                    + contentUri, e);
        }
    }

    final InputContentInfoCompat inputContentInfoCompat = new InputContentInfoCompat(contentUri,
            new ClipDescription(description, new String[] { mimeType }), null /* linkUrl */);
    InputConnectionCompat.commitContent(getCurrentInputConnection(), getCurrentInputEditorInfo(),
            inputContentInfoCompat, flag, null);
}

From source file:pw.thedrhax.util.Logger.java

/**
 * Log sharing routines/*from  ww  w.j a  v  a 2  s  .  c  om*/
 */

public static Uri writeToFile(Context context) throws IOException {
    File log_file = new File(context.getFilesDir(), "pw.thedrhax.mosmetro.txt");

    FileWriter writer = new FileWriter(log_file);
    writer.write(toString(Logger.LEVEL.DEBUG));
    writer.flush();
    writer.close();

    return FileProvider.getUriForFile(context, "pw.thedrhax.mosmetro.provider", log_file);
}

From source file:com.digigene.autoupdate.presenter.DownloadDialogPresenterImpl.java

private void doWhenDownloadIsFinishedInForcedMode(String fileName) {
    File directory = context.getExternalFilesDir(null);
    File file = new File(directory, fileName);
    Uri fileUri = Uri.fromFile(file);//www.ja  v  a2s.  co m
    if (Build.VERSION.SDK_INT >= 24) {
        fileUri = FileProvider.getUriForFile(context, context.getPackageName(), file);
    }
    Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
    activity.finish();
}

From source file:com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock5ViewHolder.java

private void startShareIntent(String fileUrl) {
    File file = null;/* www.  j  a va 2s .  com*/
    try {
        file = mFileManager.getFile(fileUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (file == null) {
        fileNotFoundToast();
        return;
    }

    Uri fileUri = FileProvider.getUriForFile(mFragment.getContext(), Config.AUTHORITY, file);
    Intent shareIntent = ShareCompat.IntentBuilder.from(mFragment.getActivity())
            .setType(mFragment.getContext().getContentResolver().getType(fileUri)).setStream(fileUri)
            .getIntent();
    shareIntent.setData(fileUri);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    mFragment.getActivity().startActivity(shareIntent);
}

From source file:org.glucosio.android.tools.ReadingToCSV.java

public Uri createCSV(final ArrayList<GlucoseReading> readings, String um) {

    File file = new File(context.getFilesDir().getAbsolutePath(), "glucosio_exported_data.csv"); //Getting a file within the dir.

    try {/*from w w w . j  a va 2  s  .c o  m*/
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);

        osw.append(context.getResources().getString(R.string.dialog_add_concentration));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_measured));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_date));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_time));
        osw.append('\n');

        FormatDateTime dateTool = new FormatDateTime(context);

        if ("mg/dL".equals(um)) {
            for (int i = 0; i < readings.size(); i++) {

                osw.append(readings.get(i).getReading() + "mg/dL");
                osw.append(',');

                osw.append(readings.get(i).getReading_type() + "");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        } else {
            GlucosioConverter converter = new GlucosioConverter();

            for (int i = 0; i < readings.size(); i++) {

                osw.append(converter.glucoseToMmolL(readings.get(i).getReading()) + "mmol/L");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        }

        osw.flush();
        osw.close();
        Log.i("Glucosio", "Done exporting readings");

    } catch (Exception e) {
        e.printStackTrace();
    }

    context.grantUriPermission(context.getPackageName(), Uri.parse(file.getAbsolutePath()),
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    return FileProvider.getUriForFile(context, context.getPackageName() + ".provider.fileprovider",
            file.getAbsoluteFile());
}

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

private static String capturePictureLabel(Context context, IStartable startable) {
    // Starts a picture intent.
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
        File photoFile = null;/*from   www.  j  a  v a 2  s. c om*/
        try {
            photoFile = PictureUtils.createImageFile(
                    AppSingleton.getInstance(context).getSensorEnvironment().getDefaultClock().getNow());
        } catch (IOException ex) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, ex.getMessage());
            }
        }
        if (photoFile != null) {
            Uri photoUri = FileProvider.getUriForFile(context, context.getPackageName(), photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                // Needed to avoid security exception on KitKat.
                takePictureIntent.setClipData(ClipData.newRawUri(null, photoUri));
            }
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            String pictureLabelPath = "file:" + photoFile.getAbsoluteFile();
            startable.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            return pictureLabelPath;
        }
    }
    return null;
}

From source file:at.bitfire.davdroid.ui.DebugInfoActivity.java

public void onShare(MenuItem item) {
    if (!TextUtils.isEmpty(report)) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_SUBJECT,
                getString(R.string.app_name) + " " + BuildConfig.VERSION_NAME + " debug info");

        // since Android 4.1, FileProvider permissions are handled in a useful way (using ClipData)
        boolean asAttachment = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;

        if (asAttachment)
            try {
                File debugInfoDir = new File(getCacheDir(), "debug-info");
                debugInfoDir.mkdir();// ww w. ja v  a  2  s  .com

                reportFile = new File(debugInfoDir, "debug.txt");
                App.log.fine("Writing debug info to " + reportFile.getAbsolutePath());
                FileWriter writer = new FileWriter(reportFile);
                writer.write(report);
                writer.close();

                sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,
                        getString(R.string.authority_log_provider), reportFile));
                sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            } catch (IOException e) {
                // creating an attachment failed, so send it inline
                asAttachment = false;

                StringBuilder builder = new StringBuilder();
                builder.append("Couldn't write debug info file:\n").append(ExceptionUtils.getStackTrace(e))
                        .append("\n\n").append(report);
                report = builder.toString();
            }

        if (!asAttachment)
            sendIntent.putExtra(Intent.EXTRA_TEXT, report);

        startActivity(Intent.createChooser(sendIntent, null));
    }
}

From source file:com.dm.material.dashboard.candybar.helpers.FileHelper.java

@Nullable
public static Uri getUriFromFile(Context context, String applicationId, File file) {
    try {//from   w  w  w  . j  a  va  2s.c  om
        return FileProvider.getUriForFile(context, applicationId + ".fileProvider", file);
    } catch (IllegalArgumentException e) {
        LogUtil.e(Log.getStackTraceString(e));
    }
    return null;
}

From source file:zuo.biao.library.ui.SelectPictureActivity.java

/**
 * ?//from   w  w w . j av a 2s  . com
 */
public void selectPicFromCamera() {
    if (!CommonUtil.isExitsSdcard()) {
        showShortToast("SD????");
        return;
    }

    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // ??
    cameraFile = new File(DataKeeper.imagePath, "photo" + System.currentTimeMillis() + ".jpg");
    cameraFile.getParentFile().mkdirs();

    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(context,
                BaseApplication.getInstance().getApplicationInfo().packageName + ".fileProvider", cameraFile);
    } else {
        uri = Uri.fromFile(cameraFile);
    }

    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    toActivity(intent, REQUEST_CODE_CAMERA);
}