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:arun.com.chameleonskinforkwlp.activities.CameraCapturerActivity.java

private void launchCamera() {
    final Intent capturePicIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Check if any app can handle this intent for us.
    final ComponentName componentName = capturePicIntent.resolveActivity(getPackageManager());
    if (componentName != null) {
        File imageFile = null;/*from w  w  w .ja va  2s.  c om*/
        try {
            imageFile = createTemporaryFile();
        } catch (IOException ex) {
            Timber.e("Error while creating image file", ex);
        }
        if (imageFile != null) {
            final Uri photoURI = FileProvider.getUriForFile(this, "arun.com.chameleonskinforkwlp.fileprovider",
                    imageFile);
            capturePicIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(capturePicIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            onCameraLaunchingFailed();
        }
    } else {
        onNoCameraDetected();
    }
}

From source file:com.commonsware.android.camcon.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CONTENT_REQUEST) {
        if (resultCode == RESULT_OK) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            Uri outputUri = FileProvider.getUriForFile(this, AUTHORITY, output);

            i.setDataAndType(outputUri, "image/jpeg");
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(i);/*  w  w  w.ja va  2s . c o m*/
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, R.string.msg_no_viewer, Toast.LENGTH_LONG).show();
            }

            finish();
        }
    }
}

From source file:com.king.base.util.SystemUtils.java

/**
 * ?/*from   w w  w  . j av a 2 s  . c  om*/
 *
 * @param activity
 * @param path
 * @param requestCode
 */
public static void imageCapture(Activity activity, String path, int requestCode) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (!TextUtils.isEmpty(path)) {
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider",
                    new File(path));
        } else {
            uri = Uri.fromFile(new File(path));
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    }
    activity.startActivityForResult(intent, requestCode);
}

From source file:de.schildbach.wallet.ui.ArchiveBackupDialogFragment.java

private void archiveWalletBackup(final File backupFile) {
    final ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(activity);
    builder.setSubject(getString(R.string.export_keys_dialog_mail_subject));
    builder.setText(getString(R.string.export_keys_dialog_mail_text) + "\n\n"
            + String.format(Constants.WEBMARKET_APP_URL, activity.getPackageName()) + "\n\n"
            + Constants.SOURCE_URL + '\n');
    builder.setType(Constants.MIMETYPE_WALLET_BACKUP);
    builder.setStream(/*from   w  ww .ja  v a 2s. com*/
            FileProvider.getUriForFile(activity, activity.getPackageName() + ".file_attachment", backupFile));
    builder.setChooserTitle(R.string.export_keys_dialog_mail_intent_chooser);
    builder.startChooser();
    log.info("invoked chooser for archiving wallet backup");
}

From source file:org.glucosio.android.presenter.ExportPresenter.java

public void onExportClicked(final boolean isExportAll) {

    if (hasStoragePermissions(mActivity)) {
        final String preferredUnit = dB.getUser(1).getPreferred_unit();
        final boolean[] isEmpty = { false };

        new AsyncTask<Void, Void, String>() {
            @Override/*from  w w w  .ja v  a2 s  .co  m*/
            protected String doInBackground(Void... params) {

                Realm realm = dB.getNewRealmInstance();
                final List<GlucoseReading> readings;
                if (isExportAll) {
                    readings = dB.getGlucoseReadings(realm);
                } else {
                    Calendar fromDate = Calendar.getInstance();
                    fromDate.set(Calendar.YEAR, fromYear);
                    fromDate.set(Calendar.MONTH, fromMonth);
                    fromDate.set(Calendar.DAY_OF_MONTH, fromDay);

                    Calendar toDate = Calendar.getInstance();
                    toDate.set(Calendar.YEAR, toYear);
                    toDate.set(Calendar.MONTH, toMonth);
                    toDate.set(Calendar.DAY_OF_MONTH, toDay);
                    readings = dB.getGlucoseReadings(realm, fromDate.getTime(), toDate.getTime());
                }

                mExportView.onExportStarted(readings.size());
                if (readings.isEmpty()) {
                    isEmpty[0] = true;
                    return null;
                }

                if (dirExists()) {
                    Log.i("glucosio", "Dir exists");
                    return new ReadingToCSV(mActivity, preferredUnit).createCSVFile(realm, readings);
                } else {
                    Log.i("glucosio", "Dir NOT exists");
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String filename) {
                super.onPostExecute(filename);
                if (filename != null) {
                    Uri uri = FileProvider.getUriForFile(mActivity.getApplicationContext(),
                            mActivity.getApplicationContext().getPackageName() + ".provider.fileprovider",
                            new File(filename));
                    mExportView.onExportFinish(uri);
                } else if (isEmpty[0]) {
                    mExportView.onNoItemsToExport();
                } else {
                    mExportView.onExportError();
                }
            }
        }.execute();
    }
}

From source file:com.commonsware.cwac.cam2.playground.PictureFragment.java

private void takePicture() {
    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
    CameraActivity.IntentBuilder b = new CameraActivity.IntentBuilder(getActivity());

    if (!prefs.getBoolean("confirm", false)) {
        b.skipConfirm();/*  w  ww . j av  a2  s  .  c o  m*/
    }

    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();
    }

    int rawEngine = Integer.valueOf(prefs.getString("forceEngine", "0"));

    switch (rawEngine) {
    case 1:
        b.forceEngine(CameraEngine.ID.CLASSIC);
        break;
    case 2:
        b.forceEngine(CameraEngine.ID.CAMERA2);
        break;
    }

    if (prefs.getBoolean("file", false)) {
        File f = new File(getActivity().getExternalFilesDir(null), "test.jpg");

        if (prefs.getBoolean("useProvider", false)) {
            Uri uri = FileProvider.getUriForFile(getActivity(), AUTHORITY, f);

            b.to(uri);
            ((Contract) getActivity()).setOutput(uri);
        } else {
            b.to(f);
            ((Contract) getActivity()).setOutput(Uri.fromFile(f));
        }
    }

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

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

    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;
    }

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

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

    int rawFlashMode = Integer.valueOf(prefs.getString("flashMode", "-1"));

    switch (rawFlashMode) {
    case 0:
        b.flashMode(FlashMode.OFF);
        break;
    case 1:
        b.flashMode(FlashMode.ALWAYS);
        break;
    case 2:
        b.flashMode(FlashMode.AUTO);
        break;
    case 3:
        b.flashMode(FlashMode.REDEYE);
        break;
    case 4:
        b.flashMode(FlashMode.TORCH);
        break;
    }

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

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

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

    case 2:
        b.zoomStyle(ZoomStyle.SEEKBAR);
        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 rawTimer = Integer.valueOf(prefs.getString("timer", "0"));

    if (rawTimer > 0) {
        b.timer(rawTimer);
    }

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

    if (confirmationQuality != null && !"Default".equals(confirmationQuality)) {
        b.confirmationQuality(Float.parseFloat(confirmationQuality));
    }

    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()).takePicture(result);
}

From source file:com.ez.gallery.PhotoBaseActivity.java

/**
 * ?/*from w ww  .  jav a 2  s . c  om*/
 */
protected void takePhotoAction() {
    if (!DeviceUtils.existSDCard()) {
        String errormsg = getString(R.string.empty_sdcard);
        toast(errormsg);
        if (mTakePhotoAction) {
            resultFailure(errormsg, true);
        }
        return;
    }

    File takePhotoFolder;
    if (StringUtils.isEmpty(mPhotoTargetFolder)) {
        takePhotoFolder = Picseler.getCoreConfig().getTakePhotoFolder();
    } else {
        takePhotoFolder = new File(mPhotoTargetFolder);
    }
    boolean suc = FileUtils.mkdirs(takePhotoFolder);
    File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");

    if (suc) {
        mTakePhotoUri = Uri.fromFile(toFile);
        Uri uri = FileProvider.getUriForFile(this, Picseler.getCoreConfig().getFileProvider(), toFile);//FileProvidercontentUri
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(captureIntent, Picseler.TAKE_REQUEST_CODE);
    } else {
        takePhotoFailure();
    }
}

From source file:es.danirod.rectball.android.AndroidSharing.java

/**
 * Save the provided screenshot and return a URI for accessing that file
 * from an Android intent. This method has been designed for being as
 * compatible as possible with older pre-23 devices and with 23+ devices
 * that use the new Android Runtime Permission system.
 *
 * @param pixmap  the screenshot to save
 * @return  an URI for accessing this screenshot from the Intent
 */// w ww .j av  a2 s.c o m
private Uri createScreenshotURI(Pixmap pixmap) {
    /*
    FIXME: THIS HACK MAKES GOD KILL KITTENS
    Should investigate on how to use the Android compatibility library.
    However, even the compatibility library seems to break compatibility
    since I cannot share anymore using SMS. Oh, well, how beautifully
    broken Android seems to be anyway.
     */

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Use the fucking new Android permission system.
        File sharingPath = new File(app.getFilesDir(), "rectball-screenshots");
        File newScreenshot = new File(sharingPath, "screenshot.png");
        FileHandle screenshotHandle = Gdx.files.absolute(newScreenshot.getAbsolutePath());
        PixmapIO.writePNG(screenshotHandle, pixmap);
        return FileProvider.getUriForFile(app, app.getString(R.string.provider), newScreenshot);
    } else {
        // Use the fucking old Android permission system.
        FileHandle sharingPath = Gdx.files.external("rectball");
        sharingPath.mkdirs();
        FileHandle newScreenshot = Gdx.files.external("rectball/screenshot.png");
        PixmapIO.writePNG(newScreenshot, pixmap);
        return Uri.fromFile(newScreenshot.file());
    }
}

From source file:com.todoroo.astrid.notes.CommentsController.java

private static void setupImagePopupForCommentView(View view, ImageView commentPictureView,
        final Uri updateBitmap, final Activity activity) {
    if (updateBitmap != null) {
        commentPictureView.setVisibility(View.VISIBLE);
        String path = getPathFromUri(activity, updateBitmap);
        commentPictureView.setImageBitmap(sampleBitmap(path, commentPictureView.getLayoutParams().width,
                commentPictureView.getLayoutParams().height));

        view.setOnClickListener(v -> {
            File file = new File(updateBitmap.getPath());
            Uri uri = FileProvider.getUriForFile(activity, Constants.FILE_PROVIDER_AUTHORITY,
                    file.getAbsoluteFile());
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            FileHelper.grantReadPermissions(activity, intent, uri);
            activity.startActivity(intent);
        });/*from   w w  w . ja  v  a 2s  .  c  o m*/
    } else {
        commentPictureView.setVisibility(View.GONE);
    }
}

From source file:com.alibaba.weex.update.UpdateService.java

private void handleActionUpdate(String url) {
    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setContentText(CheckForUpdateUtil.getStringRes(R.string.update_progress) + " 0%")
            .setTicker(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setWhen(System.currentTimeMillis()).setPriority(Notification.PRIORITY_DEFAULT)
            .setSmallIcon(R.mipmap.ic_launcher).setProgress(100, 0, false);
    manager.notify(NOTIFY_ID, builder.build());

    WXLogUtils.e("Update", "start download");
    Downloader.download(url,/*ww w. j a v a2  s  .co m*/
            new Downloader.DownloadCallback(getCacheDir().getAbsolutePath(), "playground.apk") {

                @Override
                public void onProgress(float progress) {
                    if (progress * 100 - progress >= 1) {
                        int p = (int) (progress * 100);
                        builder.setContentText(
                                CheckForUpdateUtil.getStringRes(R.string.update_progress) + p + "%");
                        builder.setProgress(100, p, false);
                        manager.notify(NOTIFY_ID, builder.build());
                        WXLogUtils.d("Update", "progress:" + p);
                    }
                }

                @Override
                public void onResponse(File file) {
                    WXLogUtils.d("Update", "success: " + file.getAbsolutePath());
                    manager.cancel(NOTIFY_ID);
                    Uri uri = Uri.fromFile(file);
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(WXEnvironment.getApplication(),
                                BuildConfig.APPLICATION_ID + ".fileprovider", file);
                        installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                    startActivity(installIntent);
                }

                @Override
                public void onError(final Exception e) {
                    WXSDKManager.getInstance().getWXRenderManager().postOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(UpdateService.this, "Failed to update:" + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }, 0);
                }
            });
}