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.odk.collect.android.widgets.ImageWebViewWidget.java

public ImageWebViewWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent();

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);/* w w w .j  a  va2  s  .c  o m*/

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    // setup capture button
    mCaptureButton = new Button(getContext());
    mCaptureButton.setId(QuestionWidget.newUniqueId());
    mCaptureButton.setText(getContext().getString(R.string.capture_image));
    mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mCaptureButton.setPadding(20, 20, 20, 20);
    mCaptureButton.setEnabled(!prompt.isReadOnly());
    mCaptureButton.setLayoutParams(params);

    // launch capture intent on click
    mCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // We give the camera an absolute filename/path where to put the
            // picture because of bug:
            // http://code.google.com/p/android/issues/detail?id=1480
            // The bug appears to be fixed in Android 2.0+, but as of feb 2,
            // 2010, G1 phones only run 1.6. Without specifying the path the
            // images returned by the camera in 1.6 (and earlier) are ~1/4
            // the size. boo.

            // if this gets modified, the onActivityResult in
            // FormEntyActivity will also need to be updated.
            Uri tempPath = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider",
                    new File(Collect.TMPFILE_PATH));
            i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, tempPath);
            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CAPTURE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "image capture"),
                        Toast.LENGTH_SHORT).show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // setup chooser button
    mChooseButton = new Button(getContext());
    mChooseButton.setId(QuestionWidget.newUniqueId());
    mChooseButton.setText(getContext().getString(R.string.choose_image));
    mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mChooseButton.setPadding(20, 20, 20, 20);
    mChooseButton.setEnabled(!prompt.isReadOnly());
    mChooseButton.setLayoutParams(params);

    // launch capture intent on click
    mChooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");

            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "choose image"), Toast.LENGTH_SHORT)
                        .show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // finish complex layout
    LinearLayout answerLayout = new LinearLayout(getContext());
    answerLayout.setOrientation(LinearLayout.VERTICAL);
    answerLayout.addView(mCaptureButton);
    answerLayout.addView(mChooseButton);
    answerLayout.addView(mErrorTextView);

    // and hide the capture and choose button if read-only
    if (prompt.isReadOnly()) {
        mCaptureButton.setVisibility(View.GONE);
        mChooseButton.setVisibility(View.GONE);
    }
    mErrorTextView.setVisibility(View.GONE);

    // retrieve answer from data model and update ui
    mBinaryName = prompt.getAnswerText();

    // Only add the imageView if the user has taken a picture
    if (mBinaryName != null) {
        mImageDisplay = new WebView(getContext());
        mImageDisplay.setId(QuestionWidget.newUniqueId());
        mImageDisplay.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mImageDisplay.getSettings().setBuiltInZoomControls(true);
        mImageDisplay.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        mImageDisplay.setVisibility(View.VISIBLE);
        mImageDisplay.setLayoutParams(params);

        // HTML is used to display the image.
        String html = "<body>" + constructImageElement() + "</body>";

        mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder + File.separator, html, "text/html",
                "utf-8", "");
        answerLayout.addView(mImageDisplay);
    }
    addAnswerView(answerLayout);
}

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

public ImageWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent();

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);/*from w w w  .  java 2  s .  c o m*/

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    // setup capture button
    mCaptureButton = new Button(getContext());
    mCaptureButton.setId(QuestionWidget.newUniqueId());
    mCaptureButton.setText(getContext().getString(R.string.capture_image));
    mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mCaptureButton.setPadding(20, 20, 20, 20);
    mCaptureButton.setEnabled(!prompt.isReadOnly());
    mCaptureButton.setLayoutParams(params);

    // launch capture intent on click
    mCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // We give the camera an absolute filename/path where to put the
            // picture because of bug:
            // http://code.google.com/p/android/issues/detail?id=1480
            // The bug appears to be fixed in Android 2.0+, but as of feb 2,
            // 2010, G1 phones only run 1.6. Without specifying the path the
            // images returned by the camera in 1.6 (and earlier) are ~1/4
            // the size. boo.

            // if this gets modified, the onActivityResult in
            // FormEntyActivity will also need to be updated.
            i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(),
                    BuildConfig.APPLICATION_ID + ".provider", new File(Collect.TMPFILE_PATH)));
            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CAPTURE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "image capture"),
                        Toast.LENGTH_SHORT).show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // setup chooser button
    mChooseButton = new Button(getContext());
    mChooseButton.setId(QuestionWidget.newUniqueId());
    mChooseButton.setText(getContext().getString(R.string.choose_image));
    mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mChooseButton.setPadding(20, 20, 20, 20);
    mChooseButton.setEnabled(!prompt.isReadOnly());
    mChooseButton.setLayoutParams(params);

    // launch capture intent on click
    mChooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");

            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "choose image"), Toast.LENGTH_SHORT)
                        .show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // finish complex layout
    LinearLayout answerLayout = new LinearLayout(getContext());
    answerLayout.setOrientation(LinearLayout.VERTICAL);
    answerLayout.addView(mCaptureButton);
    answerLayout.addView(mChooseButton);
    answerLayout.addView(mErrorTextView);

    // and hide the capture and choose button if read-only
    if (prompt.isReadOnly()) {
        mCaptureButton.setVisibility(View.GONE);
        mChooseButton.setVisibility(View.GONE);
    }
    mErrorTextView.setVisibility(View.GONE);

    // retrieve answer from data model and update ui
    mBinaryName = prompt.getAnswerText();

    // Only add the imageView if the user has taken a picture
    if (mBinaryName != null) {
        mImageView = new ImageView(getContext());
        mImageView.setId(QuestionWidget.newUniqueId());
        Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();

        File f = new File(mInstanceFolder + File.separator + mBinaryName);

        if (f.exists()) {
            Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
            if (bmp == null) {
                mErrorTextView.setVisibility(View.VISIBLE);
            }
            mImageView.setImageBitmap(bmp);
        } else {
            mImageView.setImageBitmap(null);
        }

        mImageView.setPadding(10, 10, 10, 10);
        mImageView.setAdjustViewBounds(true);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewButton", "click",
                        mPrompt.getIndex());
                Intent i = new Intent("android.intent.action.VIEW");
                Uri uri = MediaUtils
                        .getImageUriFromMediaProvider(mInstanceFolder + File.separator + mBinaryName);
                if (uri != null) {
                    Log.i(t, "setting view path to: " + uri);
                    i.setDataAndType(uri, "image/*");
                    try {
                        getContext().startActivity(i);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getContext(),
                                getContext().getString(R.string.activity_not_found, "view image"),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        answerLayout.addView(mImageView);
    }
    addAnswerView(answerLayout);
}

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

/**
 * Convert a {@link File} to an {@link Uri}
 *
 * @param file the file//  w w  w .j  a v  a  2 s .c  o m
 * @return Uri for this file
 */
public Uri getUriByFileProviderAuthority(File file) {
    return FileProvider.getUriForFile(_context, getFileProviderAuthority(), file);
}

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

/**
 * ?/*from ww w .  ja v  a2 s. c  om*/
 *
 * @param fragment
 * @param path
 * @param requestCode
 */
public static void imageCapture(Fragment fragment, String path, int requestCode) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (!TextUtils.isEmpty(path)) {
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(fragment.getContext(),
                    fragment.getContext().getPackageName() + ".fileProvider", new File(path));
        } else {
            uri = Uri.fromFile(new File(path));
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    }
    fragment.startActivityForResult(intent, requestCode);
}

From source file:com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock8ViewHolder.java

private void startShareIntent(String fileUrl) {
    File file = null;//w w  w.jav a2s.com
    try {
        file = mFileManager.getFile(fileUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (file == null) {
        fileNotFoundToast();
        return;
    }

    Uri fileUri = FileProvider.getUriForFile(mFragment.getContext(), Config.AUTHORITY, file);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(fileUri, mFragment.getContext().getContentResolver().getType(fileUri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    mFragment.getActivity().startActivity(intent);
}

From source file:com.nextgis.mobile.util.ApkDownloader.java

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    mProgress.dismiss();/*w  w w . ja  v  a  2  s. c o m*/

    if (result == null) {
        Intent install = new Intent();
        install.setAction(Intent.ACTION_VIEW);
        File apk = new File(mApkPath);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(mActivity, "com.keenfin.easypicker.provider", apk);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else
            uri = Uri.fromFile(apk);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        mActivity.startActivity(install);
    } else
        Toast.makeText(mActivity, result, Toast.LENGTH_LONG).show(); // show some info

    ControlHelper.unlockScreenOrientation(mActivity);
    if (mAutoClose)
        mActivity.finish();
}

From source file:at.jclehner.appopsxposed.BugReportBuilder.java

public Uri build() {
    final StringBuilder sb = new StringBuilder();

    sb.append("\nAOX : " + Util.getAoxVersion(mContext));
    sb.append("\nTIME: " + mReportTime);
    sb.append("\nID  : " + mDeviceId);

    collectDeviceInfo(sb);/*from  w w w  .j a  v  a2 s . c  o  m*/
    collectApkInfo(sb);
    collectAppOpsInfos(sb);

    Log.d("AOX", "-------------------------");
    Log.d("AOX", sb.toString());
    Log.d("AOX", "\n-------------------------");

    collectXposedLogs(sb);
    collectProps(sb);
    collectLogcat(sb);

    PrintWriter pw = null;

    try {
        if (!mBugReportDir.mkdirs() && !mBugReportDir.isDirectory())
            throw new RuntimeException("Failed to create " + mBugReportDir);

        pw = new PrintWriter(mBugReportFile);
        pw.println(sb);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        if (pw != null)
            pw.close();
    }

    return FileProvider.getUriForFile(mContext, "at.jclehner.appopsxposed.files", mBugReportFile);
}

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

public void run() {
    Log.d(MmsApp.TXN_TAG, "SendTransaction: run");
    RateController rateCtlr = RateController.getInstance();
    if (rateCtlr.isLimitSurpassed() && !rateCtlr.isAllowedByUser()) {
        Log.e(TAG, "Sending rate limit surpassed.");
        return;//from   ww  w  .  ja v  a2s  .c  o  m
    }

    try {
        final PduPersister persister = PduPersister.getPduPersister(mContext);
        final SendReq sendReq = (SendReq) persister.load(mUri);
        if (sendReq == null) {
            Log.w(MmsApp.TXN_TAG, "Send req is null!");
            return;
        }
        byte[] datas = new PduComposer(mContext, sendReq).make();
        mPduFile = createPduFile(datas, SEND_REQ_NAME + mUri.getLastPathSegment());
        if (mPduFile == null) {
            Log.w(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, "SendTransaction 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);
        Log.d(MmsApp.TXN_TAG,
                "send MMS with param, mUri = " + mUri + " mPdufile = " + mPduFile + ", subId = " + mSubId);
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        /// M: Add MmsService configure param @{
        SmsManager.getSmsManagerForSubscriptionId(mSubId).sendMultimediaMessage(mContext, pduFileUri, null,
                MmsConfig.getMmsServiceConfig(), sentIntent);
        /// @}
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
    }
}

From source file:com.allen.mediautil.ImageTakerHelper.java

/**
 * ???Uri//w  w w.  java 2 s.com
 *
 * @param context
 * @param authority fileProvider ??
 * @return
 */
public static Uri getOutputPictureUri(Context context, String authority) {
    //        String authority = context.getString(R.string.provider_authority);
    File saveFile = getTmpSaveFilePath(context);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        try {
            return FileProvider.getUriForFile(context, authority, saveFile);
        } catch (Exception e) {
            return Uri.fromFile(saveFile);
        }
    } else {
        return Uri.fromFile(saveFile);
    }
}

From source file:com.money.manager.ex.core.file.TextFileExport.java

private void offerFile(File file, String title) {
    //protected static final String ProviderAuthority = mContext.getApplicationContext().getPackageName() + "com.money.manager.ex.fileprovider";
    String authority = getContext().getApplicationContext().getPackageName() + ".fileprovider";

    Uri contentUri = FileProvider.getUriForFile(getContext(), authority, file);
    offerFile(contentUri, title);/*from w  w  w.ja v a  2  s.  co  m*/
}