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.just.agentweb.AgentWebUtils.java

static Uri getUriFromFileForN(Context context, File file) {
    Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".AgentWebFileProvider", file);
    return fileUri;
}

From source file:net.henryco.opalette.api.utils.Utils.java

public static void shareBitmapAction(Bitmap bitmap, String filename, Context activity, boolean saveAfter,
        Runnable... runnables) {/*from   w  w w .  ja  va  2s. c  om*/

    String file_name = filename;
    if (!file_name.endsWith(".png"))
        file_name += ".png";

    try {
        File cachePath = new File(activity.getCacheDir(), "images"); // see: res/xml/filepaths.xml

        if (cachePath.exists())
            deleteRecursive(cachePath);
        cachePath.mkdirs();

        FileOutputStream stream = new FileOutputStream(cachePath + "/" + file_name);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File imagePath = new File(activity.getCacheDir(), "images");
    File newFile = new File(imagePath, file_name);
    Uri contentUri = FileProvider.getUriForFile(activity, "net.henryco.opalette.fileprovider", newFile);

    if (contentUri != null) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
        shareIntent.setType("image/png");
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        activity.startActivity(Intent.createChooser(shareIntent, "Share"));
    }
    if (saveAfter)
        saveBitmapAction(bitmap, filename, activity, runnables);
}

From source file:com.theaetetuslabs.android_apkmaker.InstallActivity.java

private void tryInstallInternal() {
    Log.d("TAG", "signed exists? " + files.signed.exists() + ", " + files.signed.getAbsolutePath());
    System.out.println(BuildConfig.APPLICATION_ID + ".apkmakerfileprovider");
    Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".apkmakerfileprovider", files.signed);
    grantUriPermission("com.android.packageinstaller", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Intent promptInstall = getInstallIntent();
    promptInstall.setData(contentUri);//from   w  w w.  java  2s . c o  m
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(promptInstall,
            PackageManager.MATCH_DEFAULT_ONLY);
    if (list.size() > 0) {
        startActivityForResult(promptInstall, INSTALL_REQUEST);
        Log.d("TAG", "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Handled content URI");
    }

}

From source file:iop.org.iop_contributors_app.ui.dialogs.ReportIssueDialogBuilder.java

@Override
    public void onClick(final DialogInterface dialog, final int which) {
        final StringBuilder text = new StringBuilder();
        final ArrayList<Uri> attachments = new ArrayList<Uri>();
        final File cacheDir = context.getCacheDir();

        text.append(viewDescription.getText()).append('\n');

        try {//w ww .  j av  a2 s. c o m
            text.append("\n\n\n=== application info ===\n\n");

            final CharSequence applicationInfo = collectApplicationInfo();

            text.append(applicationInfo);
        } catch (final IOException x) {
            text.append(x.toString()).append('\n');
        }

        try {
            final CharSequence stackTrace = collectStackTrace();

            if (stackTrace != null) {
                text.append("\n\n\n=== stack trace ===\n\n");
                text.append(stackTrace);
            }
        } catch (final IOException x) {
            text.append("\n\n\n=== stack trace ===\n\n");
            text.append(x.toString()).append('\n');
        }

        if (viewCollectDeviceInfo.isChecked()) {
            try {
                text.append("\n\n\n=== device info ===\n\n");

                final CharSequence deviceInfo = collectDeviceInfo();

                text.append(deviceInfo);
            } catch (final IOException x) {
                text.append(x.toString()).append('\n');
            }
        }

        if (viewCollectInstalledPackages.isChecked()) {
            try {
                text.append("\n\n\n=== installed packages ===\n\n");
                CrashReporter.appendInstalledPackages(text, context);
            } catch (final IOException x) {
                text.append(x.toString()).append('\n');
            }
        }

        if (viewCollectApplicationLog.isChecked()) {
            try {
                final File logDir = context.getDir("log", Context.MODE_PRIVATE);

                for (final File logFile : logDir.listFiles()) {
                    final String logFileName = logFile.getName();
                    final File file;
                    if (logFileName.endsWith(".log.gz"))
                        file = File.createTempFile(logFileName.substring(0, logFileName.length() - 6), ".log.gz",
                                cacheDir);
                    else if (logFileName.endsWith(".log"))
                        file = File.createTempFile(logFileName.substring(0, logFileName.length() - 3), ".log",
                                cacheDir);
                    else
                        continue;

                    final InputStream is = new FileInputStream(logFile);
                    final OutputStream os = new FileOutputStream(file);

                    Io.copy(is, os);

                    os.close();
                    is.close();

                    attachments.add(FileProvider.getUriForFile(getContext(), authorities, file));
                }
            } catch (final IOException x) {
                log.info("problem writing attachment", x);
            }
        }

        if (viewCollectWalletDump.isChecked()) {
            try {
                final CharSequence walletDump = collectWalletDump();

                if (walletDump != null) {
                    final File file = File.createTempFile("wallet-dump", ".txt", cacheDir);

                    final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
                    writer.write(walletDump.toString());
                    writer.close();

                    attachments.add(FileProvider.getUriForFile(getContext(), authorities, file));
                }
            } catch (final IOException x) {
                log.info("problem writing attachment", x);
            }
        }

        if (viewCollectDb.isChecked()) {
            try {
                List data = databaseCollector.collectData();
                if (data != null && !data.isEmpty()) {
                    final File file = File.createTempFile("db-dump", ".txt", cacheDir);
                    final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
                    for (Object o : data) {
                        writer.write(o.toString() + "\n");
                    }
                    writer.close();

                    attachments.add(FileProvider.getUriForFile(getContext(), authorities, file));
                }

            } catch (Exception e) {
                log.error("Exception", e);
            }

        }

        if (CrashReporter.hasSavedBackgroundTraces()) {
            text.append("\n\n\n=== saved exceptions ===\n\n");

            try {
                CrashReporter.appendSavedBackgroundTraces(text);
            } catch (final IOException x) {
                text.append(x.toString()).append('\n');
            }
        }

        text.append("\n\nPUT ADDITIONAL COMMENTS TO THE TOP. DOWN HERE NOBODY WILL NOTICE.");

        startSend(subject(), text, attachments);
    }

From source file:com.dexin.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
        uploadImage(data.getData());// ww  w  .j  a v  a  2  s.  c  o  m
    } else if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK) {
        Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider",
                getCameraFile());
        uploadImage(photoUri);
    }
}

From source file:de.domjos.schooltools.helper.Helper.java

public static void sendMailWithAttachment(String email, String subject, File file, Context context) {
    Uri attachment = FileProvider.getUriForFile(context, context.getPackageName() + ".my.package.name.provider",
            file);//  ww w.  j  a  v  a2  s. c  om
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("vnd.android.cursor.dir/email");
    String[] to = { email };
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_EMAIL, to);
    intent.putExtra(Intent.EXTRA_STREAM, attachment);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    context.startActivity(Intent.createChooser(intent, "Send email..."));
}

From source file:com.luongbui.andersenfestival.muzei.AndersenFestivalSource.java

@Override
protected void onUpdate(int reason) {
    try {/*from w w w  .j  a  v a  2 s .  c  om*/
        int artIndex = loadArtIndex(); // Random if none exists.
        //android.util.Log.d("INDEX", ""+artIndex);
        if (reason == UPDATE_REASON_USER_NEXT || reason == UPDATE_REASON_SCHEDULED) {
            artIndex = incrArtIndex(artIndex);
            //android.util.Log.d("INDEX USER NEXT", ""+artIndex);
        }
        //For now, empty the external sub dir each time: TODO a more "flexible" cache system.
        deleteExternalSubdir(new File(getApplicationContext().getFilesDir(), PORTRAITS_SUBDIR));
        File outFile = new File(getApplicationContext().getFilesDir(),
                PORTRAITS_SUBDIR + File.separator + PORTRAITS[artIndex].getFileName());
        //TODO test if the file exits, should be false.
        //android.util.Log.d("TEST FILE EXISTS", ""+outFile.exists()+" : " + outFile.getPath());
        copyAsset(PORTRAITS_SUBDIR, PORTRAITS[artIndex].getFileName());
        //TODO test if the file exits, should be true.
        //android.util.Log.d("TEST FILE EXISTS", ""+outFile.exists()+" : " + outFile.getPath());
        fileUri = FileProvider.getUriForFile(getApplicationContext(), FILE_PROVIDER_AUTHORITIES, outFile);
        Set<String> subscribers = prefs.getStringSet(SUBS_KEY, new TreeSet<String>());
        for (String subPackage : subscribers)
            getApplicationContext().grantUriPermission(subPackage, fileUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //android.util.Log.d("SHARED FILE URI", ""+fileUri.toString());
        publishArtwork(new Artwork.Builder().imageUri(fileUri).title(PORTRAITS[artIndex].getTitle())
                .byline(PORTRAITS[artIndex].getByLine())
                .viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(PORTRAITS[artIndex].getAuthorUrl())))
                .build());
        // 12 Hours
        scheduleUpdate(System.currentTimeMillis() + 12 * 60 * 60 * 1000);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.christophergs.mbientbasic.SensorFragment.java

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (sensorResId != 2131165359) {
        chart = (LineChart) view.findViewById(R.id.data_chart);

        initializeChart();/*w w  w  .j a  v a  2 s . c o m*/
        resetData(false);
        chart.invalidate();
        chart.setDescription(null);

        Button clearButton = (Button) view.findViewById(R.id.layout_two_button_left);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshChart(true);
            }
        });
        clearButton.setText(R.string.label_clear);
    } else {
        Log.i(TAG, "Pie Chart");
    }

    ((Switch) view.findViewById(R.id.sample_control))
            .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        moveViewToLast();
                        setup();
                        chartHandler.postDelayed(updateChartTask, UPDATE_PERIOD);
                    } else {
                        chart.setVisibleXRangeMaximum(sampleCount);
                        clean();
                        if (streamRouteManager != null) {
                            streamRouteManager.remove();
                            streamRouteManager = null;
                        }
                        chartHandler.removeCallbacks(updateChartTask);
                    }
                }
            });

    Button chartButton = (Button) view.findViewById(R.id.layout_two_button_center);
    chartButton.setText(R.string.label_pie);

    Button saveButton = (Button) view.findViewById(R.id.layout_two_button_right);
    saveButton.setText(R.string.label_save);
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String filename = saveData(false);

            if (filename != null) {
                File dataFile = getActivity().getFileStreamPath(filename);
                Uri contentUri = FileProvider.getUriForFile(getActivity(),
                        "com.mbientlab.metawear.app.fileprovider2", dataFile);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, filename);
                intent.putExtra(Intent.EXTRA_STREAM, contentUri);
                startActivity(Intent.createChooser(intent, "Saving Data"));
            }
        }
    });
}

From source file:com.liferay.mobile.screens.viewsets.defaultviews.ddl.form.fields.DDLDocumentFieldView.java

@NonNull
private Action1<Boolean> launchCamera(final String intent) {
    return new Action1<Boolean>() {
        @Override/*from w  w w . ja  v a 2s .  c  o  m*/
        public void call(Boolean result) {
            if (result) {
                Intent cameraIntent = new Intent(intent);
                File file = MediaStore.ACTION_VIDEO_CAPTURE.equals(intent) ? FileUtil.createVideoFile()
                        : FileUtil.createImageFile();

                if (file != null) {
                    getField().createLocalFile(file.getAbsolutePath());
                    Uri photoURI = FileProvider.getUriForFile(getContext(),
                            getContext().getPackageName() + ".screensfileprovider", file);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    Activity activity = LiferayScreensContext.getActivityFromContext(getContext());
                    activity.startActivityForResult(cameraIntent, positionInForm);
                }
            }
            choseOriginDialog.dismiss();
        }
    };
}

From source file:com.android.gallery3d.gadget.WidgetConfigure.java

private void setChoosenPhoto(final Intent data) {
    AsyncTask.execute(new Runnable() {
        @Override//from ww  w .  j a va  2  s. co m
        public void run() {
            Resources res = getResources();

            float width = res.getDimension(R.dimen.appwidget_width);
            float height = res.getDimension(R.dimen.appwidget_height);

            // We try to crop a larger image (by scale factor), but there is still
            // a bound on the binder limit.
            float scale = Math.min(WIDGET_SCALE_FACTOR, MAX_WIDGET_SIDE / Math.max(width, height));

            int widgetWidth = Math.round(width * scale);
            int widgetHeight = Math.round(height * scale);

            File cropSrc = new File(getCacheDir(), "crop_source.png");
            File cropDst = new File(getCacheDir(), "crop_dest.png");
            mPickedItem = data.getData();
            if (!copyUriToFile(mPickedItem, cropSrc)) {
                setResult(Activity.RESULT_CANCELED);
                finish();
                return;
            }

            mCropSrc = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropSrc.getAbsolutePath()));
            mCropDst = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropDst.getAbsolutePath()));

            Intent request = new Intent(CropActivity.CROP_ACTION).putExtra(CropExtras.KEY_OUTPUT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_OUTPUT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_ASPECT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_ASPECT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_SCALE_UP_IF_NEEDED, true).putExtra(CropExtras.KEY_SCALE, true)
                    .putExtra(CropExtras.KEY_RETURN_DATA, false).setDataAndType(mCropSrc, "image/*")
                    .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            request.putExtra(MediaStore.EXTRA_OUTPUT, mCropDst);
            request.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, mCropDst));
            startActivityForResult(request, REQUEST_CROP_IMAGE);
        }
    });
}