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.kitware.tangoproject.paraviewtangorecorder.PointCloudActivity.java

private void record_SwitchChanged(boolean isChecked) {
    try {//from w  ww  . j a va 2 s  .  c  om
        mutex_on_mIsRecording.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    mIsRecording = isChecked;
    // Start Recording
    if (mIsRecording) {
        // Generate a new date number to create a new group of files
        Calendar rightNow = Calendar.getInstance();
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        int minute = rightNow.get(Calendar.MINUTE);
        int sec = rightNow.get(Calendar.SECOND);
        int milliSec = rightNow.get(Calendar.MILLISECOND);
        mNowTimeString = "" + (int) (1000000 * hour + 10000 * minute + 100 * sec + (float) milliSec / 10.0);
        mNumberOfFilesWritten = 0;
        // Enable snapshot button
        mTakeSnapButton.setEnabled(true);
    }
    // Finish Recording
    else {
        // Disable snapshot button
        mTakeSnapButton.setEnabled(false);
        // Display a waiting progress bar
        mWaitingTextView.setText(R.string.waitSavingScan);
        mWaitingLinearLayout.setVisibility(View.VISIBLE);
        // Background task for writing poses to file
        class SendCommandTask extends AsyncTask<Context, Void, Uri> {
            /** The system calls this to perform work in a worker thread and
             * delivers it the parameters given to AsyncTask.execute() */
            @Override
            protected Uri doInBackground(Context... myAppContext) {

                // Stop the Pose Recording, and write them to a file.
                writePoseToFile(mNumPoseInSequence);
                // If a snap has been asked just before, but not saved, ignore it, otherwise,
                // it will be saved at the end dof this function, and the 2nd archive will override
                // the first.
                mTimeToTakeSnap = false;
                mNumPoseInSequence = 0;
                mPoseOrientationBuffer.clear();
                mPoseOrientationBuffer.clear();
                mPoseTimestampBuffer.clear();

                // Zip all the files from this sequence
                String zipFilename = mSaveDirAbsPath + "TangoData_" + mNowTimeString + "_"
                        + mFilenameBuffer.size() + "files.zip";
                String[] fileList = mFilenameBuffer.toArray(new String[mFilenameBuffer.size()]);
                ZipWriter zipper = new ZipWriter(fileList, zipFilename);
                zipper.zip();

                // Delete the data files now that they are archived
                for (String s : mFilenameBuffer) {
                    File file = new File(s);
                    boolean deleted = file.delete();
                    if (!deleted) {
                        Log.w(TAG, "File \"" + s + "\" not deleted\n");
                    }
                }
                mFilenameBuffer.clear();

                // Send the zip file to another app
                File myZipFile = new File(zipFilename);

                return FileProvider.getUriForFile(myAppContext[0],
                        "com.kitware." + "tangoproject.paraviewtangorecorder.fileprovider", myZipFile);
            }

            /** The system calls this to perform work in the UI thread and delivers
             * the result from doInBackground() */
            @Override
            protected void onPostExecute(Uri fileURI) {
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, fileURI);
                shareIntent.setType("application/zip");
                startActivity(Intent.createChooser(shareIntent, "Send Scan To..."));
                mWaitingLinearLayout.setVisibility(View.GONE);
            }
        }
        new SendCommandTask().execute(this);

    }
    mutex_on_mIsRecording.release();

}

From source file:com.mobantica.DriverItRide.activities.ActivityProfile.java

public Uri getOutputMediaFileUri(int type) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(ActivityProfile.this, BuildConfig.APPLICATION_ID + ".provider",
                getOutputMediaFile(type));
    } else {//from  www  . j  av  a 2  s  .c o  m
        return Uri.fromFile(getOutputMediaFile(type));
    }
}

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

/**
 * Request a picture from camera-like apps
 * Result ({@link String}) will be available from {@link Activity#onActivityResult(int, int, Intent)}.
 * It has set resultCode to {@link Activity#RESULT_OK} with same requestCode, if successfully
 * The requested image savepath has to be stored at caller side (not contained in intent),
 * it can be retrieved using {@link #extractResultFromActivityResult(int, int, Intent)},
 * returns null if an error happened.//from w w  w . j a  v  a 2 s . com
 *
 * @param target Path to file to write to, if folder the filename gets app_name + millis + random filename. If null DCIM folder is used.
 */
public String requestCameraPicture(File target) {
    if (!(_context instanceof Activity)) {
        throw new RuntimeException("Error: ShareUtil.requestCameraPicture needs an Activity Context.");
    }
    String cameraPictureFilepath = null;
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(_context.getPackageManager()) != null) {
        File photoFile;
        try {
            // Create an image file name
            if (target != null && !target.isDirectory()) {
                photoFile = target;
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss", Locale.getDefault());
                File storageDir = target != null ? target
                        : new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                                "Camera");
                String imageFileName = ((new ContextUtils(_context).rstr("app_name"))
                        .replaceAll("[^a-zA-Z0-9\\.\\-]", "_") + "_").replace("__", "_")
                        + sdf.format(new Date());
                photoFile = new File(storageDir, imageFileName + ".jpg");
                if (!photoFile.getParentFile().exists() && !photoFile.getParentFile().mkdirs()) {
                    photoFile = File.createTempFile(imageFileName + "_", ".jpg", storageDir);
                }
            }

            //noinspection StatementWithEmptyBody
            if (!photoFile.getParentFile().exists() && photoFile.getParentFile().mkdirs())
                ;

            // Save a file: path for use with ACTION_VIEW intents
            cameraPictureFilepath = photoFile.getAbsolutePath();
        } catch (IOException ex) {
            return null;
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            }
            ((Activity) _context).startActivityForResult(takePictureIntent, REQUEST_CAMERA_PICTURE);
        }
    }
    _lastCameraPictureFilepath = cameraPictureFilepath;
    return cameraPictureFilepath;
}

From source file:com.gnuroot.debian.GNURootMain.java

@Override
//override this with what you want to happen when the GNURoot Debian service completes a task
public void nextStep(Intent intent) {
    super.nextStep(intent);
    if (intent.getStringExtra("packageName").equals(getPackageName())) {
        int resultCode = intent.getIntExtra("resultCode", 0);
        int requestCode = intent.getIntExtra("requestCode", 0);

        if (installingXStep1 && ((requestCode == CHECK_STATUS)
                && (resultCode != GNURootCoreActivity.STATUS_FILE_NOT_FOUND))) {
            installingXStep1 = false;//from ww w. j  av a 2 s .  c o m
            if (resultCode == GNURootCoreActivity.PASS) {
                File fileHandle = new File(getFilesDir() + "/xsupport.tar.gz");
                ArrayList<String> prerequisitesArrayList = new ArrayList<String>();
                prerequisitesArrayList.add("gnuroot_rootfs");
                prerequisitesArrayList.add("gnuroot_x_support_step1");
                installTar(FileProvider.getUriForFile(this, "com.gnuroot.debian.fileprovider", fileHandle),
                        "gnuroot_x_support", prerequisitesArrayList);
            }
        } else if (((requestCode == CHECK_STATUS) && (resultCode != GNURootCoreActivity.STATUS_FILE_NOT_FOUND))
                || (requestCode == RUN_SCRIPT)) {
            Thread thread = new Thread() {

                @Override
                public void run() {

                    // Block this thread for 1 second. There is a race case if the progressDialog is dismissed too quickly
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }

                    // After sleep finished blocking, create a Runnable to run on the UI Thread.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                        }
                    });

                }

            };
            thread.start();
        }
    }

}

From source file:com.shollmann.igcparser.ui.activity.FlightPreviewActivity.java

private void launchShareFile(String tempIgcFilePath) {
    try {//from   ww w . j  a  v  a  2s. c om
        TrackerHelper.trackShareFlight();
        Intent intentEmail = new Intent(Intent.ACTION_SEND);
        intentEmail.setType(Constants.App.TEXT_HTML);
        intentEmail.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(FlightPreviewActivity.this,
                Constants.App.FILE_PROVIDER, new File(tempIgcFilePath)));
        intentEmail.putExtra(Intent.EXTRA_SUBJECT, String.format(getString(R.string.share_email_subject),
                Uri.parse(tempIgcFilePath).getLastPathSegment()));
        startActivity(Intent.createChooser(intentEmail, getString(R.string.share)));
    } catch (Throwable t) {
        Toast.makeText(this, R.string.sorry_error_happen, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.orange.ocara.ui.activity.ResultAuditActivity.java

/**
 * To share a document by its path.<br/>
 * This will send a share intent.//from  ww  w .j  a v a2 s . co  m
 *
 * @param path the file path to share
 */
private void shareDocument(String path) {
    // create an intent, so the user can choose which application he/she wants to use to share this file
    final Intent intent = ShareCompat.IntentBuilder.from(this)
            .setType(MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)))
            .setStream(FileProvider.getUriForFile(this, "com.orange.ocara", exportFile))
            .setChooserTitle("How do you want to share?").createChooserIntent()
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivityForResult(intent, ACTION_SHARE_DOCUMENT);
}

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

private Intent createFotoSendIntent() {
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    File file = getStoredMediaFile();
    if (file != null && file.canRead()) {
        sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(DetailsActivity.this,
                "de.bahnhoefe.deutschlands.bahnhofsfotos.fileprovider", file));
    } else if (publicBitmap != null) {
        File imagePath = new File(getApplicationContext().getCacheDir(), "images");
        imagePath.mkdirs();// ww  w  .j a  va  2  s  .c  o m
        File newFile = new File(imagePath, bahnhof.getId() + ".jpg");
        try {
            saveScaledBitmap(newFile, publicBitmap);
            sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(DetailsActivity.this,
                    "de.bahnhoefe.deutschlands.bahnhofsfotos.fileprovider", newFile));
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Error saving cached bitmap", e);
        }
    }
    return sendIntent;
}

From source file:com.qiscus.sdk.ui.fragment.QiscusBaseChatFragment.java

protected void takeImage() {
    if (QiscusPermissionsUtil.hasPermissions(getActivity(), FILE_PERMISSION)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = QiscusImageUtil.createImageFile();
            } catch (IOException ex) {
                showError(getString(R.string.chat_error_failed_write));
            }//w w  w  .  ja  v a  2s  .  co m

            if (photoFile != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getActivity(),
                            Qiscus.getProviderAuthorities(), photoFile));
                }
                startActivityForResult(intent, TAKE_PICTURE_REQUEST);
            }
            hideAttachmentPanel();
        }
    } else {
        requestPermissions();
    }
}

From source file:com.uddchina.youdingdan.MyDateActivity.java

/**
 * ?/*from ww  w . j  av a  2s .c o  m*/
 */
public void doPhoto() {
    // 
    Uri uri = null;
    String saveDir = Environment.getExternalStorageDirectory() + "/youdingdan";
    File dir = new File(saveDir);
    if (!dir.exists()) {
        dir.mkdir();
    }
    String filename = "ydd_register" + pic_position + ".PNG";
    path = saveDir + "/" + filename;
    File file = new File(path);
    try {
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (Build.VERSION.SDK_INT >= 24) {
        uri = FileProvider.getUriForFile(MyDateActivity.this, "com.example.cameraalbumtest.fileprovider", file);
    } else {
        uri = Uri.fromFile(file);
    }
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    // ??
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, 2);

    /*
      String state = Environment.getExternalStorageState();
      if (state.equals(Environment.MEDIA_MOUNTED)) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 2);
      } else {
    Toast.makeText(this, "SD?", Toast.LENGTH_LONG).show();
      }*/
}

From source file:com.irccloud.android.activity.BaseActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_logout:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Logout");
        builder.setMessage("Would you like to logout of IRCCloud?");

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override//from   w  w w  .j ava2 s.  com
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("Logout", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                conn.logout();
                if (mGoogleApiClient.isConnected()) {
                    Auth.CredentialsApi.disableAutoSignIn(mGoogleApiClient)
                            .setResultCallback(new ResultCallback<Status>() {
                                @Override
                                public void onResult(Status status) {
                                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(i);
                                    finish();
                                }
                            });
                } else {
                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
                    finish();
                }
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOwnerActivity(this);
        dialog.show();
        break;
    case R.id.menu_settings:
        Intent i = new Intent(this, PreferencesActivity.class);
        startActivity(i);
        break;
    case R.id.menu_feedback:
        try {
            String bugReport = "Briefly describe the issue below:\n\n\n\n\n" + "===========\n"
                    + ((NetworkConnection.getInstance().getUserInfo() != null)
                            ? ("UID: " + NetworkConnection.getInstance().getUserInfo().id + "\n")
                            : "")
                    + "App version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName
                    + " (" + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + ")\n"
                    + "Device: " + Build.MODEL + "\n" + "Android version: " + Build.VERSION.RELEASE + "\n"
                    + "Firmware fingerprint: " + Build.FINGERPRINT + "\n";

            File logsDir = new File(getFilesDir(),
                    ".Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/");
            File log = null;
            File output = null;
            if (logsDir.exists()) {
                long max = Long.MIN_VALUE;
                for (File f : logsDir.listFiles()) {
                    if (f.lastModified() > max) {
                        max = f.lastModified();
                        log = f;
                    }
                }

                if (log != null) {
                    File f = new File(getFilesDir(), "logs");
                    f.mkdirs();
                    output = new File(f, LOG_FILENAME);
                    byte[] b = new byte[1];

                    FileOutputStream out = new FileOutputStream(output);
                    FileInputStream is = new FileInputStream(log);
                    is.skip(5);

                    while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                        if (b[0] == ' ') {
                            while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                                out.write(b);
                                if (b[0] == '\n')
                                    break;
                            }
                        }
                    }
                    is.close();
                    out.close();
                }
            }

            Intent email = new Intent(Intent.ACTION_SEND);
            email.setData(Uri.parse("mailto:"));
            email.setType("message/rfc822");
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { "IRCCloud Team <team@irccloud.com>" });
            email.putExtra(Intent.EXTRA_TEXT, bugReport);
            email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
            if (log != null) {
                email.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
            }
            startActivityForResult(Intent.createChooser(email, "Send Feedback:"), 0);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to generate email report: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
            Crashlytics.logException(e);
            NetworkConnection.printStackTraceToCrashlytics(e);
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}