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.d062654.faciliman._2_IncidentPicture.java

private void captureImage() {

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (intent.resolveActivity(ll.getContext().getPackageManager()) != null) {
        // Create the File where the photo should go

        try {//from w  w  w .  j  ava2  s .co m
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(ll.getContext(), "com.d062654.fileprovider", photoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(intent, REQUEST_TAKE_PHOTO);
        }
    }

}

From source file:ca.rmen.android.poetassistant.PoemAudioExport.java

private PendingIntent getFileShareIntent() {
    // Bring up the chooser to share the file.
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    Uri uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider",
            getAudioFile());//from  ww w . j  a va 2s  .  c  o m
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
    sendIntent.setType("audio/x-wav");
    return PendingIntent.getActivity(mContext, 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.giovanniterlingen.windesheim.controllers.DownloadController.java

@Override
protected void onPostExecute(final String result) {
    activeDownloads.remove(contentId);/*from w  w  w  . j  av a 2  s.  c o m*/
    NotificationCenter.getInstance().removeObserver(this, NotificationCenter.downloadCancelled);
    NotificationCenter.getInstance().postNotificationName(NotificationCenter.downloadFinished, studyRouteId,
            adapterPosition, contentId);

    if ("permission".equals(result)) {
        ((NatschoolActivity) activity).noPermission();
        return;
    }
    if ("cancelled".equals(result)) {
        ((NatschoolActivity) activity).downloadCanceled();
        return;
    }
    if (result != null) {
        Uri uri;
        Intent target = new Intent(Intent.ACTION_VIEW);
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(activity, "com.giovanniterlingen.windesheim.provider",
                    new File(result));
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(new File(result));
            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 {
            activity.startActivity(target);
        } catch (ActivityNotFoundException e) {
            ((NatschoolActivity) activity).noSupportedApp();
        }
    }
}

From source file:de.j4velin.mapsmeasure.Dialogs.java

/**
 * @param c     the Context//from  w  w  w.j  a v  a  2  s . c o  m
 * @param trace the current trace of points
 * @return the "save & share" dialog
 */
public static Dialog getSaveNShare(final Activity c, final Stack<LatLng> trace) {
    final Dialog d = new Dialog(c);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.dialog_save);
    d.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final File destination;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                destination = API8Wrapper.getExternalFilesDir(c);
            } else {
                destination = c.getDir("traces", Context.MODE_PRIVATE);
            }

            d.dismiss();
            AlertDialog.Builder b = new AlertDialog.Builder(c);
            b.setTitle(R.string.save);
            final View layout = c.getLayoutInflater().inflate(R.layout.dialog_enter_filename, null);
            ((TextView) layout.findViewById(R.id.location))
                    .setText(c.getString(R.string.file_path, destination.getAbsolutePath() + "/"));
            b.setView(layout);
            b.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        String fname = ((EditText) layout.findViewById(R.id.filename)).getText().toString();
                        if (fname == null || fname.length() < 1) {
                            fname = "MapsMeasure_" + System.currentTimeMillis();
                        }
                        final File f = new File(destination, fname + ".csv");
                        Util.saveToFile(f, trace);
                        d.dismiss();
                        Toast.makeText(c, c.getString(R.string.file_saved, f.getAbsolutePath()),
                                Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(c,
                                c.getString(R.string.error,
                                        e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
            b.create().show();
        }
    });
    d.findViewById(R.id.load).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {

            File[] files = c.getDir("traces", Context.MODE_PRIVATE).listFiles();

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File ext = API8Wrapper.getExternalFilesDir(c);
                // even though we checked the external storage state, ext is still sometims null, accoring to Play Store crash reports
                if (ext != null) {
                    File[] filesExtern = ext.listFiles();
                    File[] allFiles = new File[files.length + filesExtern.length];
                    System.arraycopy(files, 0, allFiles, 0, files.length);
                    System.arraycopy(filesExtern, 0, allFiles, files.length, filesExtern.length);
                    files = allFiles;
                }
            }

            if (files.length == 0) {
                Toast.makeText(c,
                        c.getString(R.string.no_files_found,
                                c.getDir("traces", Context.MODE_PRIVATE).getAbsolutePath()),
                        Toast.LENGTH_SHORT).show();
            } else if (files.length == 1) {
                try {
                    Util.loadFromFile(Uri.fromFile(files[0]), (Map) c);
                    d.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(c,
                            c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                d.dismiss();
                AlertDialog.Builder b = new AlertDialog.Builder(c);
                b.setTitle(R.string.select_file);
                final DeleteAdapter da = new DeleteAdapter(files, (Map) c);
                b.setAdapter(da, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Util.loadFromFile(Uri.fromFile(da.getFile(which)), (Map) c);
                            dialog.dismiss();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(c,
                                    c.getString(R.string.error,
                                            e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });
                b.create().show();
            }
        }
    });
    d.findViewById(R.id.share).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            try {
                final File f = new File(c.getCacheDir(), "MapsMeasure.csv");
                Util.saveToFile(f, trace);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(c, "de.j4velin.mapsmeasure.fileprovider", f));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("text/comma-separated-values");
                d.dismiss();
                c.startActivity(Intent.createChooser(shareIntent, null));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(c,
                        c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                        Toast.LENGTH_LONG).show();
            }
        }
    });
    return d;
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Share the given file as stream with given mime-type
 *
 * @param file     The file to share/*w ww  .  ja va2s.c o  m*/
 * @param mimeType The files mime type
 */
public boolean shareStream(File file, String mimeType) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(EXTRA_FILEPATH, file.getAbsolutePath());
    intent.setType(mimeType);

    try {
        Uri fileUri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), file);
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        showChooser(intent, null);
        return true;
    } catch (Exception e) { // FileUriExposed(API24) / IllegalArgument
        return false;
    }
}

From source file:com.anhubo.anhubo.ui.activity.unitDetial.UploadingActivity1.java

private void takePhoto() {
    //?? ??//  w w  w. j av  a 2  s.c  o  m
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date(System.currentTimeMillis());
    String filename = format.format(date);
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File outputImage = new File(path, filename + ".jpg");
    try {
        if (outputImage.exists()) {
            outputImage.delete();
        }
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //File?Uri??
    if (Build.VERSION.SDK_INT < 24) {

        imageUri = Uri.fromFile(outputImage);
    } else {
        imageUri = FileProvider.getUriForFile(mActivity, "com.luoli.cameraalbumtest.fileprovider", outputImage);
    }
    Intent tTntent = new Intent("android.media.action.IMAGE_CAPTURE"); //
    tTntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //?
    startActivityForResult(tTntent, CAMERA); //?

}

From source file:ru.dublgis.androidhelpers.DesktopUtils.java

public static boolean sendEmail(final Context ctx, final String to, final String subject, final String body,
        final String attach_file, final boolean force_content_provider, final String authorities) {
    //Log.d(TAG, "Will send email with subject \"" +
    //    subject + "\" to \"" + to + "\" with attach_file = \"" + attach_file + "\"" +
    //    ", force_content_provider = " + force_content_provider +
    //    ", authorities = \"" + authorities + "\"");
    try {/* w  ww . ja  v a  2s . c o  m*/
        // TODO: support multiple recipients
        String[] recipients = new String[] { to };

        final Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", to, null));
        List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(intent, 0);
        Intent chooserIntent = null;
        List<Intent> intentList = new ArrayList<Intent>();

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, recipients);
        i.putExtra(Intent.EXTRA_SUBJECT, subject);
        i.putExtra(Intent.EXTRA_TEXT, body);

        Uri workaround_grant_permission_for_uri = null;
        if (attach_file != null && !attach_file.isEmpty()) {
            if (!force_content_provider && android.os.Build.VERSION.SDK_INT < 23) {
                i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(attach_file)));
            } else {
                // Android 6+: going the longer route.
                // For more information, please see:
                // http://stackoverflow.com/questions/32981194/android-6-cannot-share-files-anymore
                i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                workaround_grant_permission_for_uri = FileProvider.getUriForFile(ctx, authorities,
                        new File(attach_file));
                i.putExtra(Intent.EXTRA_STREAM, workaround_grant_permission_for_uri);
            }
        }

        for (ResolveInfo resolveInfo : resolveInfos) {
            String packageName = resolveInfo.activityInfo.packageName;
            String name = resolveInfo.activityInfo.name;

            // Some mail clients will not read the URI unless this is done.
            // See here: https://stackoverflow.com/questions/24467696/android-file-provider-permission-denial
            if (workaround_grant_permission_for_uri != null) {
                try {
                    ctx.grantUriPermission(packageName, workaround_grant_permission_for_uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } catch (final Throwable e) {
                    Log.e(TAG, "grantUriPermission error: ", e);
                }
            }

            Intent fakeIntent = (Intent) i.clone();
            fakeIntent.setComponent(new ComponentName(packageName, name));
            if (chooserIntent == null) {
                chooserIntent = fakeIntent;
            } else {
                intentList.add(fakeIntent);
            }
        }

        if (chooserIntent == null) {
            chooserIntent = Intent.createChooser(i, null // "Select email application."
            );
            chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else if (!intentList.isEmpty()) {
            Intent fakeIntent = chooserIntent;
            chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, fakeIntent);
            Intent[] extraIntents = intentList.toArray(new Intent[intentList.size()]);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
        }

        ctx.startActivity(chooserIntent);
        return true;
    } catch (final Throwable e) {
        Log.e(TAG, "sendEmail exception: ", e);
        return false;
    }
}

From source file:org.cm.podd.report.activity.SettingActivity.java

private Uri getImageUri() {
    return FileProvider.getUriForFile(this, "org.cm.podd.report.fileprovider", createImageFile());
}

From source file:com.android.cts.intent.sender.ContentTest.java

private Uri getUriWithTextInFile(String name, String text) {
    String filename = mContext.getFilesDir() + File.separator + "texts" + File.separator + name + ".txt";
    Log.i(TAG, "Creating file " + filename + " with text \"" + text + "\"");
    final File file = new File(filename);
    file.getParentFile().mkdirs(); // If the folder doesn't exists it is created
    try {//from w ww  .  j a va  2  s  . c om
        FileWriter writer = new FileWriter(file);
        writer.write(text);
        writer.close();
    } catch (IOException e) {
        Log.e(TAG, "Could not create file " + filename + " with text " + text);
        return null;
    }
    return FileProvider.getUriForFile(mContext, "com.android.cts.intent.sender.fileprovider", file);
}

From source file:ooo.oxo.mr.ViewerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.viewer_activity);

    setTitle(null);/*from  www. j a v a  2 s .co m*/

    binding.toolbar.setNavigationOnClickListener(v -> supportFinishAfterTransition());
    binding.toolbar.inflateMenu(R.menu.viewer);

    binding.puller.setCallback(this);

    supportPostponeEnterTransition();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().getEnterTransition().addListener(new SimpleTransitionListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public void onTransitionEnd(Transition transition) {
                getWindow().getEnterTransition().removeListener(this);
                fadeIn();
            }
        });
    } else {
        fadeIn();
    }

    background = new ColorDrawable(Color.BLACK);
    binding.getRoot().setBackground(background);

    adapter = new Adapter();

    binding.pager.setAdapter(adapter);
    binding.pager.setCurrentItem(getIntent().getIntExtra("index", 0));
    binding.pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                fadeOut();
            }
        }
    });

    listener = new ObservableListPagerAdapterCallback(adapter);
    images.addOnListChangedCallback(listener);

    setEnterSharedElementCallback(new SharedElementCallback() {
        @Override
        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
            Image image = images.get(binding.pager.getCurrentItem());
            sharedElements.clear();
            sharedElements.put(String.format("%s.image", image.getObjectId()), getCurrent().getSharedElement());
        }
    });

    menuItemClicks(R.id.share).compose(bindToLifecycle())
            .compose(ensurePermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            .map(avoid -> getCurrentImage())
            .doOnNext(image -> MobclickAgent.onEvent(this, "share", image.getObjectId()))
            .observeOn(Schedulers.io()).flatMap(this::saveIfNeeded).observeOn(AndroidSchedulers.mainThread())
            .doOnNext(this::notifyMediaScanning).map(Uri::fromFile).retry().subscribe(uri -> {
                final Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
            });

    menuItemClicks(R.id.save).compose(bindToLifecycle())
            .compose(ensurePermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            .map(avoid -> getCurrentImage())
            .doOnNext(image -> MobclickAgent.onEvent(this, "save", image.getObjectId()))
            .observeOn(Schedulers.io()).flatMap(this::saveIfNeeded).observeOn(AndroidSchedulers.mainThread())
            .doOnNext(this::notifyMediaScanning).retry().subscribe(file -> {
                ToastUtil.shorts(this, R.string.save_success, file.getPath());
            });

    final WallpaperManager wm = WallpaperManager.getInstance(this);

    menuItemClicks(R.id.set_wallpaper).compose(bindToLifecycle()).map(avoid -> getCurrentImage())
            .doOnNext(image -> MobclickAgent.onEvent(this, "set_wallpaper", image.getObjectId()))
            .observeOn(Schedulers.io()).flatMap(this::download).observeOn(AndroidSchedulers.mainThread())
            .map(file -> FileProvider.getUriForFile(this, AUTHORITY_IMAGES, file)).retry().subscribe(uri -> {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    startActivity(wm.getCropAndSetWallpaperIntent(uri));
                } else {
                    try {
                        wm.setStream(getContentResolver().openInputStream(uri));
                        ToastUtil.shorts(this, R.string.set_wallpaper_success);
                    } catch (IOException e) {
                        Log.e(TAG, "Failed to set wallpaper", e);
                        ToastUtil.shorts(this, e.getMessage(), e);
                    }
                }
            });
}