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.cpjd.roblu.ui.images.ImageGalleryActivity.java

/**
 * The user clicked the plus button and wants to add a new image
 * @param v the floating action button that was clicked
 *//*  ww  w. j  a v a  2 s . c o m*/
@Override
public void onClick(View v) {
    if (!editable)
        return;

    if (EasyPermissions.hasPermissions(this, android.Manifest.permission.CAMERA)) {
        tempPictureFile = new IO(getApplicationContext()).getTempPictureFile();

        Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), "com.cpjd.roblu", tempPictureFile);

        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        startActivityForResult(camera, Constants.GENERAL);
    } else {
        Utils.showSnackbar(layout, getApplicationContext(), "Camera permission is disabled. Please enable it.",
                true, 0);
    }
}

From source file:com.allen.mediautil.ImageTakerHelper.java

/**
 * ??fileuri/*ww w.  j a v a  2  s  . co  m*/
 *
 * @param context
 * @param file
 * @param authority fileProvider name
 * @return
 */
public static Uri getOutputPictureUri(Context context, File file, String authority) {
    //        String authority = context.getString(R.string.provider_authority);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        try {
            return FileProvider.getUriForFile(context, authority, file);
        } catch (Exception e) {
            return Uri.fromFile(file);
        }
    } else {
        return Uri.fromFile(file);
    }

}

From source file:cz.maresmar.sfm.app.SfmApp.java

private void sendFeedback(Context context, String subject) {
    Timber.i("Device %s (%s) on SDK %d", Build.DEVICE, Build.MANUFACTURER, Build.VERSION.SDK_INT);

    File logFile = getLogFile();//from   w  ww  .  ja v  a2  s. c  om
    Uri logUri = FileProvider.getUriForFile(this, "cz.maresmar.sfm.FileProvider", logFile);

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "mmrmartin+dev" + '@' + "gmail.com" });
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[sfm] " + subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.feedback_mail_text));
    emailIntent.putExtra(Intent.EXTRA_STREAM, logUri);
    emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(emailIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, logUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    context.startActivity(
            Intent.createChooser(emailIntent, getString(R.string.feedback_choose_email_app_dialog)));
}

From source file:com.slownet5.pgprootexplorer.utils.FileUtils.java

public static Uri getUri(String filePath) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(CryptoFM.getContext(),
                CryptoFM.getContext().getApplicationContext().getPackageName() + ".provider",
                FileUtils.getFile(filePath));
    } else {//from w w w  . jav a2 s .co m
        return Uri.fromFile(FileUtils.getFile(filePath));
    }
}

From source file:com.giovanniterlingen.windesheim.view.DownloadsActivity.java

private void updateFilesList() {
    final File path = Environment.getExternalStoragePublicDirectory(
            ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
    File files[] = path.listFiles();
    if (files != null && files.length > 0) {
        List<NatschoolContent> contents = new ArrayList<>();
        for (File f : files) {
            if (!f.isDirectory()) {
                contents.add(new NatschoolContent(f.getName()));
            }//from  w  w w  .  j av a 2 s. c o m
        }
        if (contents.size() == 0) {
            showEmptyTextview();
        } else {
            hideEmptyTextview();
        }
        if (recyclerView == null) {
            recyclerView = findViewById(R.id.downloads_recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        }
        recyclerView.setAdapter(new NatschoolContentAdapter(this, contents) {
            @Override
            protected void onContentClick(NatschoolContent content, int position) {
                Uri uri;
                File file = new File(path.getAbsolutePath() + File.separator + content.name);
                Intent target = new Intent(Intent.ACTION_VIEW);
                if (android.os.Build.VERSION.SDK_INT >= 24) {
                    uri = FileProvider.getUriForFile(DownloadsActivity.this,
                            "com.giovanniterlingen.windesheim.provider", file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    uri = Uri.fromFile(file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                }
                String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
                String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                target.setDataAndType(uri, mimetype);

                try {
                    startActivity(target);
                } catch (ActivityNotFoundException e) {
                    if (view != null) {
                        Snackbar snackbar = Snackbar.make(view, getResources().getString(R.string.no_app_found),
                                Snackbar.LENGTH_SHORT);
                        snackbar.show();
                    }
                }
            }
        });
    } else {
        showEmptyTextview();
    }
}

From source file:org.quantumbadger.redreader.image.ShareImageCallback.java

@Override
public void onPermissionGranted() {

    final RedditAccount anon = RedditAccountManager.getAnon();

    LinkHandler.getImageInfo(activity, uri, Constants.Priority.IMAGE_VIEW, 0, new GetImageInfoListener() {

        @Override/*from ww  w.j a v  a  2  s .  c o m*/
        public void onFailure(final @CacheRequest.RequestFailureType int type, final Throwable t,
                final Integer status, final String readableMessage) {
            final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, uri);
            General.showResultDialog(activity, error);
        }

        @Override
        public void onSuccess(final ImageInfo info) {

            CacheManager.getInstance(activity)
                    .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon, null,
                            Constants.Priority.IMAGE_VIEW, 0, DownloadStrategyIfNotCached.INSTANCE,
                            Constants.FileType.IMAGE, CacheRequest.DOWNLOAD_QUEUE_IMMEDIATE, false, false,
                            activity) {

                        @Override
                        protected void onCallbackException(Throwable t) {
                            BugReportActivity.handleGlobalError(context, t);
                        }

                        @Override
                        protected void onDownloadNecessary() {
                            General.quickToast(context, R.string.download_downloading);
                        }

                        @Override
                        protected void onDownloadStarted() {
                        }

                        @Override
                        protected void onFailure(@CacheRequest.RequestFailureType int type, Throwable t,
                                Integer status, String readableMessage) {

                            final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                                    url.toString());
                            General.showResultDialog(activity, error);
                        }

                        @Override
                        protected void onProgress(boolean authorizationInProgress, long bytesRead,
                                long totalBytes) {
                        }

                        @Override
                        protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                                UUID session, boolean fromCache, String mimetype) {

                            String filename = General.filenameFromString(info.urlOriginal);
                            File dst = new File(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES), filename);

                            if (dst.exists()) {
                                int count = 0;

                                while (dst.exists()) {
                                    count++;
                                    dst = new File(
                                            Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_PICTURES),
                                            count + "_" + filename.substring(1));
                                }
                            }

                            Uri sharedImage = FileProvider.getUriForFile(context,
                                    "org.quantumbadger.redreader.provider", dst);

                            try {
                                final InputStream cacheFileInputStream = cacheFile.getInputStream();

                                if (cacheFileInputStream == null) {
                                    notifyFailure(CacheRequest.REQUEST_FAILURE_CACHE_MISS, null, null,
                                            "Could not find cached image");
                                    return;
                                }

                                General.copyFile(cacheFileInputStream, dst);

                                Intent shareIntent = new Intent();
                                shareIntent.setAction(Intent.ACTION_SEND);
                                shareIntent.putExtra(Intent.EXTRA_STREAM, sharedImage);
                                shareIntent.setType(mimetype);
                                activity.startActivity(Intent.createChooser(shareIntent,
                                        activity.getString(R.string.action_share_image)));

                            } catch (IOException e) {
                                notifyFailure(CacheRequest.REQUEST_FAILURE_STORAGE, e, null,
                                        "Could not copy file");
                                return;
                            }

                            activity.sendBroadcast(
                                    new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, sharedImage));

                            General.quickToast(context, context.getString(R.string.action_save_image_success)
                                    + " " + dst.getAbsolutePath());
                        }
                    });

        }

        @Override
        public void onNotAnImage() {
            General.quickToast(activity, R.string.selected_link_is_not_image);
        }
    });
}

From source file:com.mbientlab.metawear.app.SensorFragment.java

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    chart = (LineChart) view.findViewById(R.id.data_chart);

    initializeChart();/*from  w w  w .  ja  va  2s  . co m*/
    resetData(false);
    chart.invalidate();

    view.findViewById(R.id.data_clear).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chart.resetTracking();
            chart.clear();
            resetData(true);
            chart.invalidate();
        }
    });
    ((Switch) view.findViewById(R.id.sample_control))
            .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        moveViewToLast();
                        setup();
                        chartHandler.postDelayed(updateChartTask, UPDATE_PERIOD);
                    } else {
                        chart.setVisibleXRangeMaximum(sampleCount);
                        clean();
                        if (streamRouteManager != null) {
                            streamRouteManager.remove();
                            streamRouteManager = null;
                        }
                        chartHandler.removeCallbacks(updateChartTask);
                    }
                }
            });

    view.findViewById(R.id.data_save).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String filename = saveData();

            if (filename != null) {
                File dataFile = getActivity().getFileStreamPath(filename);
                Uri contentUri = FileProvider.getUriForFile(getActivity(),
                        "com.mbientlab.metawear.app.fileprovider", dataFile);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, filename);
                intent.putExtra(Intent.EXTRA_STREAM, contentUri);
                startActivity(Intent.createChooser(intent, "Saving Data"));
            }
        }
    });
}

From source file:org.odk.collect.android.widgets.AnnotateWidget.java

private void captureImage() {
    errorTextView.setVisibility(View.GONE);
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    // We give the camera an absolute filename/path where to put the
    // picture because of bug:
    // http://code.google.com/p/android/issues/detail?id=1480
    // The bug appears to be fixed in Android 2.0+, but as of feb 2,
    // 2010, G1 phones only run 1.6. Without specifying the path the
    // images returned by the camera in 1.6 (and earlier) are ~1/4
    // the size. boo.

    Uri uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider",
            new File(Collect.TMPFILE_PATH));
    // if this gets modified, the onActivityResult in
    // FormEntyActivity will also need to be updated.
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
    FileUtils.grantFilePermissions(intent, uri, getContext());

    imageCaptureHandler.captureImage(intent, RequestCodes.IMAGE_CAPTURE, R.string.annotate_image);
}

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

@Override
public void onClick(final DialogInterface dialog, final int which) {
    final StringBuilder text = new StringBuilder();
    final ArrayList<Uri> attachments = new ArrayList<Uri>();
    final File cacheDir = context.getCacheDir();

    text.append(viewDescription.getText()).append('\n');

    try {//w  w w  . j  ava 2 s  .  c o  m
        final CharSequence contextualData = collectContextualData();
        if (contextualData != null) {
            text.append("\n\n\n=== contextual data ===\n\n");
            text.append(contextualData);
        }
    } catch (final IOException x) {
        text.append(x.toString()).append('\n');
    }

    try {
        text.append("\n\n\n=== application info ===\n\n");

        final CharSequence applicationInfo = collectApplicationInfo();

        text.append(applicationInfo);
    } catch (final IOException x) {
        text.append(x.toString()).append('\n');
    }

    try {
        final CharSequence stackTrace = collectStackTrace();

        if (stackTrace != null) {
            text.append("\n\n\n=== stack trace ===\n\n");
            text.append(stackTrace);
        }
    } catch (final IOException x) {
        text.append("\n\n\n=== stack trace ===\n\n");
        text.append(x.toString()).append('\n');
    }

    if (viewCollectDeviceInfo.isChecked()) {
        try {
            text.append("\n\n\n=== device info ===\n\n");

            final CharSequence deviceInfo = collectDeviceInfo();

            text.append(deviceInfo);
        } catch (final IOException x) {
            text.append(x.toString()).append('\n');
        }
    }

    if (viewCollectInstalledPackages.isChecked()) {
        try {
            text.append("\n\n\n=== installed packages ===\n\n");
            CrashReporter.appendInstalledPackages(text, context);
        } catch (final IOException x) {
            text.append(x.toString()).append('\n');
        }
    }

    if (viewCollectApplicationLog.isChecked()) {
        final File logDir = new File(context.getFilesDir(), "log");
        if (logDir.exists())
            for (final File logFile : logDir.listFiles())
                if (logFile.isFile() && logFile.length() > 0)
                    attachments.add(FileProvider.getUriForFile(context,
                            context.getPackageName() + ".file_attachment", logFile));
    }

    if (viewCollectWalletDump.isChecked()) {
        try {
            final CharSequence walletDump = collectWalletDump();

            if (walletDump != null) {
                final File reportDir = new File(cacheDir, "report");
                reportDir.mkdir();
                final File file = File.createTempFile("wallet-dump.", ".txt", reportDir);

                final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
                writer.write(walletDump.toString());
                writer.close();

                attachments.add(FileProvider.getUriForFile(context,
                        context.getPackageName() + ".file_attachment", file));
            }
        } catch (final IOException x) {
            log.info("problem writing attachment", x);
        }
    }

    if (CrashReporter.hasSavedBackgroundTraces()) {
        text.append("\n\n\n=== saved exceptions ===\n\n");

        try {
            CrashReporter.appendSavedBackgroundTraces(text);
        } catch (final IOException x) {
            text.append(x.toString()).append('\n');
        }
    }

    text.append("\n\nPUT ADDITIONAL COMMENTS TO THE TOP. DOWN HERE NOBODY WILL NOTICE.");

    startSend(subject(), text, attachments);
}

From source file:free.rm.skytube.gui.businessobjects.updates.UpgradeAppTask.java

/**
 * Ask the user whether he wants to install the latest SkyTube's APK file.
 *
 * @param apkFile   APK file to install.
 *///from  ww  w  .j  a  va2  s . c  o m
private void displayUpgradeAppDialog(File apkFile) {
    Uri apkFileURI = (android.os.Build.VERSION.SDK_INT >= 24)
            ? FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".provider", apkFile) // we now need to call FileProvider.getUriForFile() due to security changes in Android 7.0+
            : Uri.fromFile(apkFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(apkFileURI, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK /* asks the user to open the newly updated app */
            | Intent.FLAG_GRANT_READ_URI_PERMISSION /* to avoid a crash due to security changes in Android 7.0+ */);
    context.startActivity(intent);
}