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:us.theparamountgroup.android.inventory.EditorActivity.java

public void takePicture(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Log.i(LOG_TAG, "in takePicture");
    try {//from w  w  w. j a  va 2 s. c o m
        File file = createImageFile();
        Log.i(LOG_TAG, "in takePicture just back from createImagefile");

        mUri = FileProvider.getUriForFile(getApplication().getApplicationContext(),
                "us.theparamountgroup.android.inventory.fileprovider", file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

@Override
public void onFileDownloaded(File file, String mimeType) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        intent.setDataAndType(Uri.fromFile(file), mimeType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } else {//w  ww  . j  a  v a 2  s  .c om
        intent.setDataAndType(FileProvider.getUriForFile(getActivity(), Qiscus.getProviderAuthorities(), file),
                mimeType);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        showError(getString(R.string.chat_error_no_handler));
    }
}

From source file:net.maa123.tatuky.ComposeActivity.java

private void initiateCameraApp() {
    // We don't need to ask for permission in this case, because the used calls require
    // android.permission.WRITE_EXTERNAL_STORAGE only on SDKs *older* than Kitkat, which was
    // way before permission dialogues have been introduced.
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;/*from   ww w  . ja v a2  s  .  c om*/
        try {
            photoFile = createNewImageFile();
        } catch (IOException ex) {
            displayTransientError(R.string.error_media_upload_opening);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            photoUploadUri = FileProvider.getUriForFile(this, "net.maa123.tatuky.fileprovider", photoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUploadUri);
            startActivityForResult(intent, MEDIA_TAKE_PHOTO_RESULT);
        }
    }
}

From source file:com.android.dialer.voicemail.VoicemailPlaybackPresenter.java

/**
 * Sends the intent for sharing the voicemail file.
 *///from w  w  w  .  j  av  a2 s  .  co  m
protected void sendShareIntent(final Uri voicemailUri) {
    mVoicemailAsyncTaskUtil
            .getVoicemailFilePath(new VoicemailAsyncTaskUtil.OnGetArchivedVoicemailFilePathListener() {
                @Override
                public void onGetArchivedVoicemailFilePath(String filePath) {
                    mView.enableUiElements();
                    if (filePath == null) {
                        mView.setFetchContentTimeout();
                        return;
                    }
                    Uri voicemailFileUri = FileProvider.getUriForFile(mContext,
                            mContext.getString(R.string.contacts_file_provider_authority), new File(filePath));
                    mContext.startActivity(Intent.createChooser(getShareIntent(voicemailFileUri),
                            mContext.getResources().getText(R.string.call_log_share_voicemail)));
                }
            }, voicemailUri);
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private void initiateCameraApp() {
    // We don't need to ask for permission in this case, because the used calls require
    // android.permission.WRITE_EXTERNAL_STORAGE only on SDKs *older* than Kitkat, which was
    // way before permission dialogues have been introduced.
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;//www.  j a  v a  2 s. c om
        try {
            photoFile = createNewImageFile();
        } catch (IOException ex) {
            displayTransientError(R.string.error_media_upload_opening);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            photoUploadUri = FileProvider.getUriForFile(this, "com.keylesspalace.tusky.fileprovider",
                    photoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUploadUri);
            startActivityForResult(intent, MEDIA_TAKE_PHOTO_RESULT);
        }
    }
}

From source file:com.android.mms.ui.MessageUtils.java

public static Uri getPreviewFileUri(Context context, MediaModel model) {
    deleteAllSharedFiles(context, TEMP_FILE_TAG);
    final File tempPreviewFile = createTempFileExposed(context, model.getUri(), model.getSrc());
    if (tempPreviewFile == null || !tempPreviewFile.exists() || tempPreviewFile.length() <= 0) {
        MmsLog.e(TAG, "getPreviewFileUri, file is not exists or empty " + tempPreviewFile);
        return null;
    }/*from   ww  w  .  j a  va2s.c o  m*/
    return FileProvider.getUriForFile(context, MMS_SHARED_FILE_PROVIDER_AUTHORITIES, tempPreviewFile);
}

From source file:org.wso2.iot.agent.api.ApplicationManager.java

/**
 * Installs or updates an application to the device.
 *
 * @param url - APK Url should be passed in as a String.
 *///from  w w w .  j  a v a 2 s  .c o  m
private void downloadApp(String url) {
    RequestQueue queue = null;
    try {
        queue = ServerUtilities.getCertifiedHttpClient();
    } catch (IDPTokenManagerException e) {
        Log.e(TAG, "Failed to retrieve HTTP client", e);
    }

    InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, url,
            new Response.Listener<byte[]>() {
                @Override
                public void onResponse(byte[] response) {
                    if (response != null) {
                        FileOutputStream outStream = null;
                        InputStream inStream = null;
                        try {
                            String directory = Environment.getExternalStorageDirectory().getPath()
                                    + resources.getString(R.string.application_mgr_download_location);
                            File file = new File(directory);
                            file.mkdirs();
                            File outputFile = new File(file,
                                    resources.getString(R.string.application_mgr_download_file_name));

                            if (outputFile.exists()) {
                                outputFile.delete();
                            }

                            outStream = new FileOutputStream(outputFile);
                            inStream = new ByteArrayInputStream(response);

                            byte[] buffer = new byte[BUFFER_SIZE];
                            int lengthFile;

                            while ((lengthFile = inStream.read(buffer)) != READ_FAILED) {
                                outStream.write(buffer, BUFFER_OFFSET, lengthFile);
                                downloadOngoing = true;
                            }

                            String filePath = directory
                                    + resources.getString(R.string.application_mgr_download_file_name);
                            Preference.putString(context,
                                    context.getResources().getString(R.string.app_install_status),
                                    context.getResources()
                                            .getString(R.string.app_status_value_download_completed));

                            //android 7 and later versions require file URIs from a provider
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                Uri apkURI = FileProvider.getUriForFile(context,
                                        context.getApplicationContext().getPackageName() + ".provider",
                                        new File(filePath));
                                triggerInstallation(apkURI);

                            } else {
                                triggerInstallation(Uri.fromFile(new File(filePath)));
                            }

                        } catch (IOException e) {
                            String error = "File download/save failure in AppUpdator.";
                            Log.e(TAG, error, e);
                            Preference.putString(context,
                                    context.getResources().getString(R.string.app_install_status),
                                    context.getResources()
                                            .getString(R.string.app_status_value_download_failed));
                            Preference.putString(context,
                                    context.getResources().getString(R.string.app_install_failed_message),
                                    error);
                        } catch (IllegalArgumentException e) {
                            String error = "Error occurred while sending 'Get' request due to empty host name";
                            Log.e(TAG, error);
                            Preference.putString(context,
                                    context.getResources().getString(R.string.app_install_status),
                                    context.getResources()
                                            .getString(R.string.app_status_value_download_failed));
                            Preference.putString(context,
                                    context.getResources().getString(R.string.app_install_failed_message),
                                    error);
                        } finally {
                            StreamHandler.closeOutputStream(outStream, TAG);
                            StreamHandler.closeInputStream(inStream, TAG);
                            downloadOngoing = false;
                        }
                    } else {
                        Preference.putString(context,
                                context.getResources().getString(R.string.app_install_status),
                                context.getResources().getString(R.string.app_status_value_download_failed));
                        Preference.putString(context,
                                context.getResources().getString(R.string.app_install_failed_message),
                                "File download failed.");
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, error.toString());
                    Preference.putString(context, context.getResources().getString(R.string.app_install_status),
                            context.getResources().getString(R.string.app_status_value_download_failed));
                    Preference.putString(context,
                            context.getResources().getString(R.string.app_install_failed_message),
                            error.toString());
                    downloadOngoing = false;
                }
            }, null) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "*/*");
            headers.put("User-Agent", "Mozilla/5.0 ( compatible ), Android");
            return headers;
        }

        @Override
        protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
            //Initialise local responseHeaders map with response headers received
            responseHeaders = response.headers;
            //Pass the response data here
            if (response.statusCode == 200) {
                return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
            } else {
                VolleyError error = new VolleyError("Invalid application file URL.");
                return Response.error(error);
            }
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(Constants.RetryPolicy.DEFAULT_TIME_OUT,
            Constants.RetryPolicy.DEFAULT_MAX_RETRIES, Constants.RetryPolicy.DEFAULT_BACKOFF_MULT) {
        public void retry(VolleyError error) throws VolleyError {
            Log.w(TAG, "Retrying download the apk... " + getCurrentRetryCount());
            super.retry(error);
        }
    });

    queue.add(request);
}

From source file:org.naturenet.ui.MainActivity.java

/**
 * This method gets all the recent images the user has taken.
 * @return listOfAllImages - the list of all the most recent images taken on the phone.
 *///  w  w w. j av  a  2s . c  o  m
public List<Uri> getRecentImagesUris() {
    Uri uri;
    Cursor cursor;
    List<Uri> listOfAllImages = Lists.newArrayList();
    uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String[] projection = new String[] { MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN };
    cursor = this.getContentResolver().query(uri, projection, null, null,
            MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
    if (cursor != null) {
        cursor.moveToFirst();
        try {
            do {
                listOfAllImages.add(FileProvider.getUriForFile(this,
                        getApplicationContext().getPackageName() + ".provider", new File(
                                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)))));
            } while (cursor.moveToNext() && listOfAllImages.size() < 8);
        } catch (CursorIndexOutOfBoundsException ex) {
            Timber.e(ex, "Could not read data from MediaStore, image gallery may be empty");
        } finally {
            cursor.close();
        }
    } else {
        Timber.e("Could not get MediaStore content!");
    }
    return listOfAllImages;
}

From source file:com.intuit.qboecoui.email.SalesFormEmail.java

/**
 * invoke the pdf viewer to show the downloaded PDF.
 *///  w  ww  . ja va  2 s.  co m
private void startExternalPreviewActivity() {

    if (hasPreviewLaunched) {
        return;
    }
    hasPreviewLaunched = true;
    // track the launch of external pdf viewer
    //SalesFormEmail.SFM_Flow_tracking = Util.buildTrackingFlow(SalesFormEmail.SFM_Flow_tracking, QBMTrackConstants.SFM_OPEN_PDF );
    BaseApplicationModule.getTrackingModule().trackLink(QBMTrackConstants.SALES_FORM_EMAIL_PAGE_NAME,
            QBMTrackConstants.SFM_OPEN_PDF);

    try {
        mPDFFileName = AppPreferences.getStringPreference(this.getApplicationContext(),
                BaseAppPreferences.PREFS_QBSHAREDLIB, QBODocumentLinkEntity.KEY_PDF_FILENAME, null);
        File file = new File(mPDFFileName);
        Uri fileUri = FileProvider.getUriForFile(this,
                this.getApplicationContext().getResources().getString(R.string.file_provider_authorities),
                file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(fileUri, this.getContentResolver().getType(fileUri));
        startActivity(intent);
    } catch (final ActivityNotFoundException e) {
        displayError(R.string.error_pdf_viewer_not_present, R.string.error_title_error, false);
    }
}

From source file:com.terraremote.terrafieldreport.OpenGroundReport.java

public void submitDailyGroundTailgate() {

    gatherValues();/*from w  w w  .j  a v  a  2s.  c o m*/
    GroundJsonObjectBuilder();

    String dailyTailgateText = createDailyTailgate(name, userSelectedDateGround, submissionDate, reSubmit,
            transitDay, phoneNumber, mobNumber, workingAlone, colleagues, locationStart, gpsLatitude,
            gpsLongitude, hiVisApparel, clothingForSeason, safetyRatedFootwear, personalSurvivalKit,
            hearingProtection, hardHat, ppeComments, rentalVehicle, rentalAgency, vehicleMake, vehicleModel,
            vehicleColour, vehicleLicensePlate, vehicleOperatorName, cityOfDeparture, cityOfArrival,
            projectLocation, projectDescription, estimatedWorkDuration, checkInContactRole, checkInContactName,
            satellitePhone, satellitePhoneNumber, radio, firstAidKit, fireExtinguisher, transportingFuel,
            tdgPlacards, spillKit, workingInTraffic, pylons, trafficSigns, appropriateVehicle, remoteArea,
            workingInIsolation, extremeWeather, transmissionLines, activeMineSite, activeLoggingArea, wildlife,
            fatigue, politicalConflict, riskLevel, preventionMeasures, postRiskLevel, generalComments);

    writeJsonFileToExternalStorage();

    // New email method (attaching .json file instead of .csv)
    File Dir = new File(String.valueOf(getExternalFilesDir(null)) + "/GroundReports");
    String jsonReportTextFileName = "OpenGround_Report.json";
    File jsonReportFile = new File(Dir, jsonReportTextFileName);

    Uri uri = FileProvider.getUriForFile(OpenGroundReport.this, BuildConfig.APPLICATION_ID + ".provider",
            jsonReportFile);

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("plain/text");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { getString(R.string.email_address) });
    intent.putExtra(Intent.EXTRA_SUBJECT, "Open Ground Report" + "-" + "MOB(" + mobNumber + ")-" + name + "-"
            + userSelectedDateGround + "-" + "Field_Report");
    intent.putExtra(Intent.EXTRA_TEXT, dailyTailgateText);

    if (!jsonReportFile.exists() || !jsonReportFile.canRead()) {
        return;
    }

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(Intent.createChooser(intent, getString(R.string.pick_email_provider)));
    }
}