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.android.mms.transaction.NotificationTransaction.java

public void run() {
    MmsLog.d(MmsApp.TXN_TAG, "NotificationTransaction: run");
    DownloadManager downloadManager = DownloadManager.getInstance();
    boolean autoDownload = allowAutoDownload(mContext, mSubId);
    try {// w w w.j  a  v  a  2s . c om
        if (LOCAL_LOGV) {
            Log.v(TAG, "Notification transaction launched: " + this);
        }

        // By default, we set status to STATUS_DEFERRED because we
        // should response MMSC with STATUS_DEFERRED when we cannot
        // download a MM immediately.
        int status = STATUS_DEFERRED;
        // Don't try to download when data is suspended, as it will fail, so defer download
        if (!autoDownload) {
            // M: change API for ALPS01889178, use sub id.
            downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED, mSubId);
            sendNotifyRespInd(status);
            getState().setState(SUCCESS);
            getState().setContentUri(mUri);
            notifyObservers();
            return;
        }

        // M: change API for ALPS01889178, use sub id.
        downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING, mSubId);

        if (mOpNotificationTransactionExt.run(mIsCancelling, mUri, mContext, getUri(), mContentLocation)) {
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            mIsCancelling = false;
            return;
        }

        if (LOCAL_LOGV) {
            Log.v(TAG, "Content-Location: " + mContentLocation);
        }
        mPduFile = createPduFile(null, RETRIEVE_RESULT_NAME + mUri.getLastPathSegment());
        mPduFile.setWritable(true, false);

        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());

        Log.d(MmsApp.TXN_TAG, "NotificationTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent downloadedIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId);
        Log.d(MmsApp.TXN_TAG, "download MMS with param, mContentLocation = " + mContentLocation + ", mUri = "
                + mUri + ", subId" + mSubId);

        /// M: Add MmsService configure param @{
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        manager.downloadMultimediaMessage(mContext, mContentLocation, pduFileUri,
                MmsConfig.getMmsServiceConfig(), downloadedIntent);
        /// @}

        // sendNotifyRespInd(status);

        // Make sure this thread isn't over the limits in message count.
        Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);
        MmsWidgetProvider.notifyDatasetChanged(mContext);
    } catch (Throwable t) {
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
        Log.e(TAG, Log.getStackTraceString(t));
    }
}

From source file:ee.ria.DigiDoc.fragment.ContainerDetailsFragment.java

@OnClick(R.id.sendButton)
public void onShareContainer() {
    refreshContainerFacade();//from   w  ww.j a  va  2s.  c  o  m
    Uri uriToFile = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID,
            containerFacade.getContainerFile());
    String mediaType = "application/zip";
    Intent shareIntent = createSendIntent(uriToFile, mediaType);
    List<ResolveInfo> allAvailableResolvers = getActivity().getPackageManager()
            .queryIntentActivities(shareIntent, 0);
    List<Intent> targetedIntents = createTargetedSendIntentsForResolvers(allAvailableResolvers, uriToFile,
            mediaType);
    startActivity(createChooser(targetedIntents, getText(R.string.upload_to)));
}

From source file:com.app.encontreibvrr.uploadImagem.MainActivityStorage.java

@AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
    Log.d(TAG, "launchCamera");

    // Check that we have permission to read images from external storage.
    String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    if (!EasyPermissions.hasPermissions(this, perm)) {
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage), RC_STORAGE_PERMS, perm);
        return;// w  w w  .j  a  v  a  2  s.  com
    }

    // Choose file storage location, must be listed in res/xml/file_paths.xml
    File dir = new File(Environment.getExternalStorageDirectory() + "/photos");
    File file = new File(dir, UUID.randomUUID().toString() + ".jpg");
    try {
        // Create directory if it does not exist.
        if (!dir.exists()) {
            dir.mkdir();
        }
        boolean created = file.createNewFile();
        Log.d(TAG, "file.createNewFile:" + file.getAbsolutePath() + ":" + created);
    } catch (IOException e) {
        Log.e(TAG, "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
    }

    // Create content:// URI for file, required since Android N
    // See: https://developer.android.com/reference/android/support/v4/content/FileProvider.html
    mFileUri = FileProvider.getUriForFile(this, "com.google.firebase.quickstart.firebasestorage.fileprovider",
            file);

    // Create and launch the intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

    startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}

From source file:com.doctoror.fuckoffmusicplayer.presentation.media.browser.MediaBrowserImpl.java

@NonNull
private MediaItem createMediaItemAlbum(@NonNull final Cursor c) {
    final MediaDescriptionCompat.Builder description = new MediaDescriptionCompat.Builder()
            .setMediaId(/*from   w  ww . j a  v  a2  s .  c om*/
                    MediaBrowserConstants.MEDIA_ID_PREFIX_ALBUM.concat(c.getString(AlbumsProviderKt.COLUMN_ID)))
            .setTitle(c.getString(AlbumsProviderKt.COLUMN_ALBUM));
    final String art = c.getString(AlbumsProviderKt.COLUMN_ALBUM_ART);
    if (!TextUtils.isEmpty(art)) {
        final Uri uri = FileProvider.getUriForFile(mContext,
                mContext.getPackageName().concat(".provider.album_thumbs"), new File(art));
        for (final String p : mMediaBrowserCallerPackageNames) {
            mContext.grantUriPermission(p, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        description.setIconUri(uri);
    }
    return new MediaItem(description.build(), MediaItem.FLAG_PLAYABLE);
}

From source file:com.android.mms.transaction.RetrieveTransaction.java

public void run() {
    MmsLog.i(MmsApp.TXN_TAG, "RetrieveTransaction: run()");
    try {/*w w  w  .j av a2 s.  c o  m*/
        NotificationInd nInd = (NotificationInd) PduPersister.getPduPersister(mContext).load(mUri);
        if (nInd.getExpiry() < System.currentTimeMillis() / 1000L) {
            MmsLog.d(MmsApp.TXN_TAG, "The message is expired!");
            sendExpiredRes();
            // Change the downloading state of the M-Notification.ind.
            DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            notifyObservers();
            return;
        }

        // Change the downloading state of the M-Notification.ind.
        DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);

        /// M: For OP009, check if cancel download requested. @{
        /*            if (MmsConfig.isCancelDownloadEnable() && mIsCancelling) {
        mTransactionState.setState(TransactionState.SUCCESS);
        mTransactionState.setContentUri(mUri);
                
        if (MmsConfig.isCancelDownloadEnable()) {
            sMmsFailedNotifyPlugin.popupToast(mContext,
                IMmsFailedNotifyExt.CANCEL_DOWNLOAD, null);
        }
        mIsCancelling = false;
        final Uri trxnUri = getUri();
        sCancelDownloadPlugin.markStateExt(trxnUri, sCancelDownloadPlugin.STATE_COMPLETE);
        DownloadManager.getInstance().markState(trxnUri, DownloadManager.STATE_UNSTARTED);
                
        return;
                    }*/
        /// @}

        if (mOpRetrieveTransactionExt.run(mIsCancelling, mUri, mContext, getUri(), mContentLocation)) {
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            mIsCancelling = false;
            return;
        }

        mPduFile = createPduFile(null, RETRIEVE_RESULT_NAME + mUri.getLastPathSegment());
        mPduFile.setWritable(true, false);
        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());
        Log.d(MmsApp.TXN_TAG, "RetrieveTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent downloadedIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId);
        Log.d(MmsApp.TXN_TAG, "download MMS with param, mContentLocation = " + mContentLocation + ", mUri = "
                + mUri + ", subId" + mSubId);
        /// M: Add MmsService configure param @{
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        manager.downloadMultimediaMessage(mContext, mContentLocation, pduFileUri,
                MmsConfig.getMmsServiceConfig(), downloadedIntent);
        /// @}

        // Make sure this thread isn't over the limits in message count.
        Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);

        /// OP009 MMS Feature: cancel download Mms @{
        /*            if (MmsConfig.isCancelDownloadEnable()) {
        sCancelDownloadPlugin.addHttpClient(mContentLocation, mUri);
                    }*/
        /// @}

        // Send ACK to the Proxy-Relay to indicate we have fetched the
        // MM successfully.
        // Don't mark the transaction as failed if we failed to send it.
        // sendAcknowledgeInd(retrieveConf);
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        mTransactionState.setState(TransactionState.FAILED);
        mTransactionState.setContentUri(mUri);
        notifyObservers();
    }
}

From source file:com.owncloud.android.datamodel.OCFile.java

public Uri getExposedFileUri(Context context) {
    if (mLocalPath == null || mLocalPath.length() == 0) {
        return null;
    }//w ww .  j  a  v  a  2  s . co m
    if (mExposedFileUri == null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            // TODO - use FileProvider with any Android version, with deeper testing -> 2.2.0
            mExposedFileUri = Uri
                    .parse(ContentResolver.SCHEME_FILE + "://" + WebdavUtils.encodePath(mLocalPath));
        } else {
            // Use the FileProvider to get a content URI
            try {
                mExposedFileUri = FileProvider.getUriForFile(context,
                        context.getString(R.string.file_provider_authority), new File(mLocalPath));
            } catch (IllegalArgumentException e) {
                Log_OC.e(TAG, "File can't be exported");
            }
        }
    }
    return mExposedFileUri;
}

From source file:com.nicefontaine.seanachie.ui.imagestory.ImageStoryFragment.java

private void photo() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        try {/*from  w  ww  .j a  va  2 s  . c  o m*/
            File photoFile = FileUtils.createImageFile();
            cacheImagePath(photoFile.getAbsolutePath());
            Uri photoURI = FileProvider.getUriForFile(getActivity(), REPOSITORY, photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            getActivity().startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        } catch (IOException e) {
            Timber.e(e);
        }
    }
}

From source file:com.popdeem.sdk.core.utils.PDSocialUtils.java

/**
 * Create a chooser Intent for sharing an Image file to Instagram
 *
 * @param path Path to Image file/*from  w ww.j a  v a 2s  . co m*/
 * @return Chooser Intent
 */
public static Intent createInstagramIntent(Context context, String path) {
    File file = new File(path);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.setPackage("com.instagram.android");
    Log.i("PROVIDER", "createInstagramIntent: ");
    Uri sharedFileUri = FileProvider.getUriForFile(context,
            context.getApplicationContext().getPackageName() + ".fileprovider", file);

    intent.putExtra(Intent.EXTRA_STREAM, sharedFileUri);
    return intent;
    //        return Intent.createChooser(intent, "Share to");
}

From source file:com.google.samples.apps.gameloopmanager.TestLoopsActivity.java

private void runScenario(String packageName, int scenario) throws IOException {
    String filename = String.format("results%d.json", scenario > 0 ? scenario : 0);
    File f = new File(Environment.getExternalStorageDirectory(), filename);
    //noinspection ResultOfMethodCallIgnored
    f.createNewFile();/* ww w  .  j a  va  2  s.com*/
    String myPackageName = getPackageName();
    Uri fileUri = FileProvider.getUriForFile(this, myPackageName, f);

    Intent intent = new Intent("com.google.intent.action.TEST_LOOP").setPackage(packageName)
            .setDataAndType(fileUri, "application/javascript").setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    if (scenario >= 0) {
        intent.putExtra("scenario", scenario);
    }

    runningTestLoop = true;
    startActivityForResult(intent, TEST_LOOP_REQUEST_CODE);
}

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

/**
 * Open a View intent for given file//from   ww  w.ja v a 2 s.c  o m
 *
 * @param file The file to share
 */
public boolean viewFileInOtherApp(File file, @Nullable String type) {
    // On some specific devices the first won't work
    Uri fileUri = null;
    try {
        fileUri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), file);
    } catch (Exception ignored) {
        try {
            fileUri = Uri.fromFile(file);
        } catch (Exception ignored2) {
        }
    }

    if (fileUri != null) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        intent.setData(fileUri);
        intent.putExtra(EXTRA_FILEPATH, file.getAbsolutePath());
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(fileUri, type);
        showChooser(intent, null);
        return true;
    }
    return false;
}