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:org.wahtod.wififixer.utility.LogUtil.java

public static void sendIssueReport(Activity activity, String report, File file) {
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType(activity.getString(R.string.log_mimetype));
    sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { activity.getString(R.string.email) });
    sendIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.subject));
    Uri uri = FileProvider.getUriForFile(activity, "org.wahtod.wififixer.files", file);
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
    List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(sendIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }// w  ww. ja v a  2  s. c o  m
    sendIntent.putExtra(Intent.EXTRA_TEXT, LogUtil.getBuildInfo() + "\n\n" + report);
    activity.startActivityForResult(Intent.createChooser(sendIntent, activity.getString(R.string.emailintent)),
            1);
}

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

private Uri getFileUri(@NonNull Context context, @NonNull File file) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".file.provider", mOutputFile);
    } else {/*from   ww w  .  java2  s . c  om*/
        return Uri.fromFile(file);
    }
}

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

public void run() {
    MmsLog.d(MmsApp.TXN_TAG, "ReadRecTransaction: process()");
    // prepare for ReadRec
    int readReportState = 0;
    String messageId = null;/*from w  w w.j a  v a 2 s . co m*/
    long msgId = 0;
    EncodedStringValue[] sender = new EncodedStringValue[1];
    Cursor cursor = null;
    cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(), mUri,
            new String[] { Mms.MESSAGE_ID, Mms.READ_REPORT, Mms._ID }, null, null, null);
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                messageId = cursor.getString(0);
                readReportState = cursor.getInt(1);
                msgId = cursor.getLong(2);
            }
            // if curosr==null, this means the mms is deleted during
            // processing.
            // exception will happened. catched by out catch clause.
            // so do not catch exception here.
        } finally {
            cursor.close();
        }
    }
    MmsLog.d(MmsApp.TXN_TAG,
            "messageid:" + messageId + ",and readreport flag:" + readReportState + ", mSubId = " + mSubId);

    cursor = null;
    cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(),
            Uri.parse("content://mms/" + msgId + "/addr"), new String[] { Mms.Addr.ADDRESS, Mms.Addr.CHARSET },
            Mms.Addr.TYPE + " = " + PduHeaders.FROM, null, null);
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                String address = cursor.getString(0);
                int charSet = cursor.getInt(1);
                MmsLog.d(MmsApp.TXN_TAG, "find address:" + address + ",charset:" + charSet);
                sender[0] = new EncodedStringValue(charSet, PduPersister.getBytes(address));
            }
            // if cursor == null exception will catched by out catch clause.
        } finally {
            cursor.close();
        }
    }
    try {
        ReadRecInd readRecInd = new ReadRecInd(
                new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()),
                messageId.getBytes(), PduHeaders.CURRENT_MMS_VERSION, PduHeaders.READ_STATUS_READ, // always
                // set
                // read.
                sender);
        readRecInd.setDate(System.currentTimeMillis() / 1000);
        Uri uri = PduPersister.getPduPersister(mContext).persist(readRecInd, Mms.Outbox.CONTENT_URI, true,
                MmsPreferenceActivity.getIsGroupMmsEnabled(mContext), null);

        byte[] datas = new PduComposer(mContext, readRecInd).make();
        mPduFile = createPduFile(datas, READREP_REQ_NAME + uri.getLastPathSegment());
        if (mPduFile == null) {
            Log.e(MmsApp.TXN_TAG, "create pdu file req failed!");
            return;
        }
        //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, "ReadRecTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        SmsManager.getSmsManagerForSubscriptionId(mSubId).sendMultimediaMessage(mContext, pduFileUri, null,
                null, sentIntent);
    } catch (InvalidHeaderValueException e) {
        Log.e(TAG, "Invalide header value", e);
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
    } catch (MmsException e) {
        Log.e(TAG, "Persist message failed", e);
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
    }
}

From source file:com.darizotas.metadatastrip.FileDetailFragment.java

/**
 * Creates the Share Intent that contains the 
 * @param container Metadata container.//from  w w  w.j  av a  2  s.  co m
 * @return Intent for sharing.
 */
private Intent getShareIntent(MetaDataContainer container) {
    Intent intent = new Intent(Intent.ACTION_SEND);

    intent.putExtra(Intent.EXTRA_SUBJECT, "[" + getResources().getString(R.string.app_name) + "] "
            + getResources().getString(R.string.share_subject) + " " + container.getFileName());
    intent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_text) + " "
            + DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));

    try {
        // http://stackoverflow.com/questions/3272534/what-content-type-value-should-i-send-for-my-xml-sitemap
        // http://www.grauw.nl/blog/entry/489
        intent.setType("application/xml");
        //https://developer.android.com/training/sharing/send.html#send-binary-content
        //https://developer.android.com/reference/android/support/v4/content/FileProvider.html
        mStripFile = getMetadataFile(container);
        Uri uri = FileProvider.getUriForFile(getActivity(), "com.darizotas.metadatastrip", mStripFile);
        intent.putExtra(Intent.EXTRA_STREAM, uri);

    } catch (IllegalArgumentException e) {
        // Invalidates the intent.
        intent.setType(null);
    }
    return intent;
}

From source file:com.agateau.equiv.ui.Kernel.java

public void shareCustomProductList(Context context) {
    File file = context.getFileStreamPath(CUSTOM_PRODUCTS_CSV);
    Uri contentUri = FileProvider.getUriForFile(context, "com.agateau.equiv.fileprovider", file);
    final Resources res = context.getResources();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { Constants.CUSTOM_PRODUCTS_EMAIL });
    intent.putExtra(Intent.EXTRA_SUBJECT, res.getString(R.string.share_email_subject));
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    context.startActivity(Intent.createChooser(intent, res.getString(R.string.share_via)));
}

From source file:org.odk.collect.android.widgets.ArbitraryFileWidget.java

private void openFile() {

    Uri fileUri = Uri.fromFile(new File(getInstanceFolder() + File.separator + binaryName));
    Uri contentUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider",
            new File(getInstanceFolder() + File.separator + binaryName));
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(contentUri, getMimeType(getSourcePathFromUri(fileUri)));
    FileUtils.grantFileReadPermissions(intent, contentUri, getContext());

    if (new ActivityAvailability(getContext()).isActivityAvailable(intent)) {
        getContext().startActivity(intent);
    } else {//from   w w  w  .ja v a2 s  . c  om
        String message = getContext().getString(R.string.activity_not_found,
                getContext().getString(R.string.open_file));
        ToastUtils.showLongToast(message);
        Timber.w(message);
    }
}

From source file:org.chaos.fx.cnbeta.details.ImageFragment.java

private void shareToMore() {
    final String path = getImageCachePath();
    storeImageToLocalIfNeed(path, new Callback() {
        @Override// w w w  . j ava2 s.  c om
        public void onSuccess() {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/jpg");
            if (Build.VERSION.SDK_INT >= 24) {
                shareIntent.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(getActivity().getApplicationContext(),
                                BuildConfig.APPLICATION_ID + ".provider", new File(path)));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
            }
            startActivity(Intent.createChooser(shareIntent, getString(R.string.share_to)));
        }

        @Override
        public void onError(Exception e) {
            failedToStoreImage(e);
        }
    });
}

From source file:it.uniroma3.android.gpstracklogger.adapters.AdapterTrack.java

private void sendMail(int position) {
    Track track = Session.getController().getImportedTracks().get(position);
    final Intent intent = new Intent(Intent.ACTION_SEND);

    intent.setType("*/*");
    intent.setAction(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT, "Traccia: " + track.getName());

    ArrayList<Uri> chosenFile = new ArrayList<>();
    String path = track.getPath();
    File file = new File(path);
    Uri uri = null;/*from   w  w w. j  a  v  a 2s . c  o  m*/
    if (path.contains(AppSettings.getDirectory()))
        uri = FileProvider.getUriForFile(activity, "it.uniroma3.android.gpstracklogger.GPSMainActivity", file);
    else
        uri = Uri.fromFile(file);

    chosenFile.add(uri);
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, chosenFile);
    activity.startActivity(Intent.createChooser(intent, "Condividi via..."));
}

From source file:com.king.base.util.SystemUtils.java

/**
 * apk//from   w  w  w  . j a  v  a2s . c o m
 * @param context
 * @param file
 */
public static void installApk(Context context, File file) {

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Uri uriData = null;
    String type = "application/vnd.android.package-archive";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        uriData = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);
    } else {
        uriData = Uri.fromFile(file);
    }
    intent.setDataAndType(uriData, type);
    context.startActivity(intent);
}

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

private Uri createShareUri(String dataFileName) {
    File attachment = extractAttachment(dataFileName);
    if (attachment == null) {
        throw new FailedToCreateViewIntentException(getText(R.string.attachment_extract_failed));
    }/*from   ww w  . j  a v  a2 s  .  co m*/
    Uri contentUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID, attachment);
    getContext().grantUriPermission(BuildConfig.APPLICATION_ID, contentUri,
            Intent.FLAG_GRANT_READ_URI_PERMISSION);
    return contentUri;
}