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:io.mapsquare.osmcontributor.ui.activities.PhotoActivity.java

private void takePicture() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        try {//from   w w w  . jav a  2s  .com
            photoFile = createImageFile();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, "io.mapsquare.osmcontributor.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_CAMERA);
        }
    }
}

From source file:io.jawg.osmcontributor.ui.activities.PhotoActivity.java

private void takePicture() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        try {//from   www .  j  a  va2 s.  c om
            photoFile = createImageFile();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_CAMERA);
        }
    }
}

From source file:com.door43.translationstudio.ui.dialogs.BackupDialog.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
    v = inflater.inflate(R.layout.dialog_backup, container, false);

    // get target translation to backup
    Bundle args = getArguments();//from  w w w .  j  a v  a 2 s  .  c  o m
    if (args != null && args.containsKey(ARG_TARGET_TRANSLATION_ID)) {
        String targetTranslationId = args.getString(ARG_TARGET_TRANSLATION_ID, null);
        targetTranslation = App.getTranslator().getTargetTranslation(targetTranslationId);
        if (targetTranslation == null) {
            throw new InvalidParameterException(
                    "The target translation '" + targetTranslationId + "' is invalid");
        }
    } else {
        throw new InvalidParameterException("The target translation id was not specified");
    }

    targetTranslation.setDefaultContributor(App.getProfile().getNativeSpeaker());

    mBackupToCloudButton = (LinearLayout) v.findViewById(R.id.backup_to_cloud);
    LinearLayout exportProjectButton = (LinearLayout) v.findViewById(R.id.backup_to_sd);
    Button backupToAppButton = (Button) v.findViewById(R.id.backup_to_app);
    Button backupToDeviceButton = (Button) v.findViewById(R.id.backup_to_device);
    LinearLayout exportToPDFButton = (LinearLayout) v.findViewById(R.id.export_to_pdf);
    LinearLayout exportToUsfmButton = (LinearLayout) v.findViewById(R.id.export_to_usfm);

    Button logout = (Button) v.findViewById(R.id.logout_button);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            App.setProfile(null);
            Intent logoutIntent = new Intent(getActivity(), ProfileActivity.class);
            startActivity(logoutIntent);
        }
    });

    final String filename = targetTranslation.getId() + "." + Translator.ARCHIVE_EXTENSION;

    initProgressWatcher(R.string.backup);

    if (savedInstanceState != null) {
        // check if returning from device alias dialog
        settingDeviceAlias = savedInstanceState.getBoolean(STATE_SETTING_DEVICE_ALIAS, false);
        mDialogShown = eDialogShown
                .fromInt(savedInstanceState.getInt(STATE_DIALOG_SHOWN, eDialogShown.NONE.getValue()));
        mAccessFile = savedInstanceState.getString(STATE_ACCESS_FILE, null);
        mDialogMessage = savedInstanceState.getString(STATE_DIALOG_MESSAGE, null);
        isOutputToDocumentFile = savedInstanceState.getBoolean(STATE_OUTPUT_TO_DOCUMENT_FILE, false);
        mDestinationFolderUri = Uri.parse(savedInstanceState.getString(STATE_OUTPUT_FOLDER_URI, ""));
        restoreDialogs();
    }

    Button dismissButton = (Button) v.findViewById(R.id.dismiss_button);
    dismissButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    backupToDeviceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO: 11/18/2015 eventually we need to support bluetooth as well as an adhoc network
            showDeviceNetworkAliasDialog();
        }
    });

    // backup buttons
    mBackupToCloudButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (App.isNetworkAvailable()) {
                // make sure we have a gogs user
                if (App.getProfile().gogsUser == null) {
                    showDoor43LoginDialog();
                    return;
                }

                doPullTargetTranslationTask(targetTranslation, MergeStrategy.RECURSIVE);
            } else {
                showNoInternetDialog(); // replaced snack popup which could be hidden behind dialog
            }
        }
    });

    exportToPDFButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PrintDialog printDialog = new PrintDialog();
            Bundle printArgs = new Bundle();
            printArgs.putString(PrintDialog.ARG_TARGET_TRANSLATION_ID, targetTranslation.getId());
            printDialog.setArguments(printArgs);
            showDialogFragment(printDialog, PrintDialog.TAG);
        }
    });

    exportProjectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            doSelectDestinationFolder(false);
        }
    });

    exportToUsfmButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            doSelectDestinationFolder(true);
        }
    });

    if (targetTranslation.isObsProject()) {
        LinearLayout exportToUsfmSeparator = (LinearLayout) v.findViewById(R.id.export_to_usfm_separator);
        exportToUsfmSeparator.setVisibility(View.GONE);
        exportToUsfmButton.setVisibility(View.GONE);
    }

    backupToAppButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File exportFile = new File(App.getSharingDir(), filename);
            try {
                App.getTranslator().exportArchive(targetTranslation, exportFile);
            } catch (Exception e) {
                Logger.e(TAG, "Failed to export the target translation " + targetTranslation.getId(), e);
            }
            if (exportFile.exists()) {
                Uri u = FileProvider.getUriForFile(getActivity(), "com.door43.translationstudio.fileprovider",
                        exportFile);
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("application/zip");
                i.putExtra(Intent.EXTRA_STREAM, u);
                startActivity(Intent.createChooser(i, "Email:"));
            } else {
                Snackbar snack = Snackbar.make(getActivity().findViewById(android.R.id.content),
                        R.string.translation_export_failed, Snackbar.LENGTH_LONG);
                ViewUtil.setSnackBarTextColor(snack, getResources().getColor(R.color.light_primary_text));
                snack.show();
            }
        }
    });

    // connect to existing tasks
    PullTargetTranslationTask pullTask = (PullTargetTranslationTask) TaskManager
            .getTask(PullTargetTranslationTask.TASK_ID);
    RegisterSSHKeysTask keysTask = (RegisterSSHKeysTask) TaskManager.getTask(RegisterSSHKeysTask.TASK_ID);
    CreateRepositoryTask repoTask = (CreateRepositoryTask) TaskManager.getTask(CreateRepositoryTask.TASK_ID);
    PushTargetTranslationTask pushTask = (PushTargetTranslationTask) TaskManager
            .getTask(PushTargetTranslationTask.TASK_ID);
    ExportProjectTask projectExportTask = (ExportProjectTask) TaskManager.getTask(ExportProjectTask.TASK_ID);
    ExportToUsfmTask usfmExportTask = (ExportToUsfmTask) TaskManager.getTask(ExportToUsfmTask.TASK_ID);

    if (pullTask != null) {
        taskWatcher.watch(pullTask);
    } else if (keysTask != null) {
        taskWatcher.watch(keysTask);
    } else if (repoTask != null) {
        taskWatcher.watch(repoTask);
    } else if (pushTask != null) {
        taskWatcher.watch(pushTask);
    } else if (projectExportTask != null) {
        taskWatcher.watch(projectExportTask);
    } else if (usfmExportTask != null) {
        taskWatcher.watch(usfmExportTask);
    }

    return v;
}

From source file:uk.ac.hutton.ics.buntata.activity.LogEntryActivity.java

private void share(File zip) {
    createdFiles.add(zip);/*www  .j  a  v a 2s . c  om*/

    /* Ask Android to share it for us */
    ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(this)
            .setSubject(getString(R.string.app_name));
    /* Use the provider to make the file available to the other app (Android requirement) */
    String providerName = getPackageName() + ".fileprovider";
    Uri uri = FileProvider.getUriForFile(this, providerName, zip);

    builder.setStream(uri).setType("text/plain");

    try {
        startActivityForResult(builder.getIntent(), REQUEST_CODE_SHARE);
    } catch (ActivityNotFoundException e) {
        /* No app can handle the request, there's nothing we can do now... */
        SnackbarUtils.create(getSnackbarParentView(), R.string.snackbar_no_app_found,
                ContextCompat.getColor(this, android.R.color.white),
                ContextCompat.getColor(this, R.color.snackbar_red), Snackbar.LENGTH_LONG).show();
    }
}

From source file:com.luke.lukef.lukeapp.NewUserActivity.java

/**
 * Creates the intent to start camera//w ww . j  av a2s .co m
 */
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go

        if (photoFile != null) {
            this.photoPath = photoFile.getAbsolutePath();
            // Continue only if the File was successfully created
            Uri photoURI = FileProvider.getUriForFile(this, "com.luke.lukef.lukeapp", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            createImageFile();
            dispatchTakePictureIntent();
        }
    }
}

From source file:io.nuclei.cyto.share.PackageTargetManager.java

/**
 * Set default intent data/*from   ww  w . j av  a2 s. co m*/
 */
protected void onSetDefault(Context context, String packageName, String authority, Intent intent, String text) {
    intent.putExtra(Intent.EXTRA_TEXT, text);
    if (!TextUtils.isEmpty(mSubject))
        intent.putExtra(Intent.EXTRA_SUBJECT, mSubject);
    if (mUri != null || mFile != null) {
        Uri uri = mUri;
        String type = "*/*";
        if (mFile != null) {
            uri = FileProvider.getUriForFile(context, authority, mFile);
            final int lastDot = mFile.getName().lastIndexOf('.');
            if (lastDot >= 0) {
                String extension = mFile.getName().substring(lastDot + 1);
                String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (mimeType != null)
                    type = mimeType;
            }
        }
        intent.setDataAndType(intent.getData(), type);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        if (packageName != null) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    } else {
        intent.setType("text/plain");
    }
    if (!TextUtils.isEmpty(mEmail)) {
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mEmail });
        intent.setData(Uri.parse("mailto:"));
    }
}

From source file:uk.ac.hutton.ics.buntata.activity.LogDetailsActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();// w  w w.j av a  2  s .  com
        return true;
    case R.id.action_add_image:
        /* We don't want to show images that have already been selected, so exclude those */
        ArrayList<File> toExclude = new ArrayList<>();

        for (LogEntryImage image : images)
            toExclude.add(new File(image.getPath()));
        for (LogEntryImage image : newlyCreatedImages)
            toExclude.add(new File(image.getPath()));

        ImagePicker.create(this).folderMode(true).returnMode(ReturnMode.CAMERA_ONLY).excludeFiles(toExclude)
                .theme(R.style.ImagePickerTheme).start(REQUEST_CODE_PICKER);
        return true;
    case R.id.action_share:
        String text = log.getNote() + " " + getString(R.string.social_media_postfix);
        ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(this).setText(text)
                .setSubject(log.getNodeName());

        if (images.size() > 0) {
            /* Use the provider to make the file available to the other app (Android requirement) */
            String providerName = getPackageName() + ".fileprovider";
            Uri uri = FileProvider.getUriForFile(this, providerName, new File(images.get(0).getPath()));

            builder.setStream(uri).setType("image/jpeg");
        } else {
            /* If there are no images, set the type to be plain text */
            builder.setType("text/plain");
        }

        try {
            startActivity(builder.getIntent());
        } catch (ActivityNotFoundException e) {
            /* No app can handle the request, there's nothing we can do now... */
            SnackbarUtils.create(getSnackbarParentView(), R.string.snackbar_no_app_found,
                    ContextCompat.getColor(this, android.R.color.white),
                    ContextCompat.getColor(this, R.color.snackbar_red), Snackbar.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.DetailsActivity.java

public void takePicture() {
    if (!canSetPhoto()) {
        return;// w  w  w.j  a  v a  2  s  .c  om
    }

    if (isMyDataIncomplete()) {
        checkMyData();
    } else {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getCameraMediaFile();
        if (file != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "de.bahnhoefe.deutschlands.bahnhofsfotos.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            intent.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, getResources().getString(R.string.app_name));
            intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, bahnhof.getTitle());
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivityForResult(intent, REQUEST_TAKE_PICTURE);
        } else {
            Toast.makeText(this, R.string.unable_to_create_folder_structure, Toast.LENGTH_LONG).show();
        }
    }
}

From source file:org.rm3l.ddwrt.tiles.status.wireless.WirelessIfaceQrCodeActivity.java

private void setShareFile(File file) {
    if (mShareActionProvider == null) {
        return;//ww  w  .  j av  a 2  s.  com
    }

    final Uri uriForFile = FileProvider.getUriForFile(this, "org.rm3l.fileprovider", file);

    mShareActionProvider
            .setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener() {
                @Override
                public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
                    grantUriPermission(intent.getComponent().getPackageName(), uriForFile,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    return true;
                }
            });

    final Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, uriForFile);
    sendIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("QR Code for Wireless Network '%s'", mSsid));

    sendIntent.setData(uriForFile);
    sendIntent.setType("image/png");
    sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    setShareIntent(sendIntent);

}

From source file:com.frostwire.android.gui.util.UIUtils.java

public static Uri getFileUri(Context context, String filePath, boolean useFileProvider) {
    return useFileProvider
            ? FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider",
                    new File(filePath))
            : Uri.fromFile(new File(filePath));
}