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.orpheusdroid.screenrecorder.adapter.VideoRecyclerAdapter.java

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Video video = videos.get(position);
    switch (holder.getItemViewType()) {
    case VIEW_ITEM:
        final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
        //Set video file name
        itemViewHolder.tv_fileName.setText(video.getFileName());
        //If thumbnail has failed for some reason, set empty image resource to imageview
        if (videos.get(position).getThumbnail() != null) {
            itemViewHolder.iv_thumbnail.setImageBitmap(video.getThumbnail());
        } else {//from   ww  w  .  j  av a  2s. c om
            itemViewHolder.iv_thumbnail.setImageResource(0);
            Log.d(Const.TAG, "thumbnail error");
        }

        // Hide the play image over thumbnail and overflow menu if multiselect enabled
        if (isMultiSelect) {
            itemViewHolder.iv_play.setVisibility(View.INVISIBLE);
            itemViewHolder.overflow.setVisibility(View.INVISIBLE);
        } else {
            itemViewHolder.iv_play.setVisibility(View.VISIBLE);
            itemViewHolder.overflow.setVisibility(View.VISIBLE);
        }

        // Set foreground color to identify selected items
        if (video.isSelected()) {
            itemViewHolder.selectableFrame.setForeground(
                    new ColorDrawable(ContextCompat.getColor(context, R.color.multiSelectColor)));
        } else {
            itemViewHolder.selectableFrame.setForeground(
                    new ColorDrawable(ContextCompat.getColor(context, android.R.color.transparent)));
        }

        itemViewHolder.overflow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu = new PopupMenu(context, view);
                popupMenu.inflate(R.menu.popupmenu);
                popupMenu.show();
                popupMenu.getMenu().getItem(3).setEnabled(PreferenceManager.getDefaultSharedPreferences(context)
                        .getBoolean(context.getString(R.string.preference_save_gif_key), false));
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.share:
                            shareVideo(itemViewHolder.getAdapterPosition());
                            break;
                        case R.id.delete:
                            confirmDelete(holder.getAdapterPosition());
                            break;
                        case R.id.edit:
                            Toast.makeText(context, "Edit video for " + itemViewHolder.getAdapterPosition(),
                                    Toast.LENGTH_SHORT).show();

                            Intent editIntent = new Intent(context, EditVideoActivity.class);
                            editIntent.putExtra(Const.VIDEO_EDIT_URI_KEY,
                                    Uri.fromFile(video.getFile()).toString());
                            Log.d(Const.TAG, "Uri: " + Uri.fromFile(video.getFile()));
                            videosListFragment.startActivityForResult(editIntent,
                                    Const.VIDEO_EDIT_REQUEST_CODE);
                            break;
                        case R.id.savegif:
                            Mp4toGIFConverter gif = new Mp4toGIFConverter(context);
                            gif.setVideoUri(Uri.fromFile(video.getFile()));
                            gif.convertToGif();
                        }
                        return true;
                    }
                });
            }
        });

        //Show user a chooser to play the video with
        itemViewHolder.videoCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Video video = videos.get(itemViewHolder.getAdapterPosition());

                // If multiselect is enabled, select the items pressed by user
                if (isMultiSelect) {

                    // main count of the selected items
                    // If the video is already selected, reduce count else increment count
                    if (video.isSelected())
                        count--;
                    else
                        count++;

                    // Enable disable selection based on previous choice
                    video.setSelected(!video.isSelected());
                    notifyDataSetChanged();
                    mActionMode.setTitle("" + count);

                    // If the count is 0, disable muliselect
                    if (count == 0)
                        setMultiSelect(false);
                    return;
                }

                File videoFile = video.getFile();
                Log.d("Videos List", "video position clicked: " + itemViewHolder.getAdapterPosition());

                Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider",
                        videoFile);
                Log.d(Const.TAG, fileUri.toString());
                Intent openVideoIntent = new Intent();
                openVideoIntent.setAction(Intent.ACTION_VIEW).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        .setDataAndType(fileUri, context.getContentResolver().getType(fileUri));
                context.startActivity(openVideoIntent);
            }
        });

        // LongClickListener to enable multiselect
        itemViewHolder.videoCard.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (!isMultiSelect) {
                    setMultiSelect(true);
                    video.setSelected(true);
                    count++;
                    mActionMode.setTitle("" + count);
                    notifyDataSetChanged();
                }
                return true;
            }
        });

        break;
    case VIEW_SECTION:
        SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
        sectionViewHolder.section.setText(generateSectionTitle(video.getLastModified()));
        break;
    }
}

From source file:net.micode.soundrecorder.RecorderService.java

private void showStoppedNotification() {
    stopForeground(true);/*from   w  w w .  j  a v a2  s  .  c o m*/
    mLowStorageNotification = null;

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.stat_sys_call_record).setContentTitle(getString(R.string.app_name))
            .setWhen(System.currentTimeMillis()).setContentText(getString(R.string.notification_stopped));

    //Support for Android 7 and above  see below
    //https://medium.com/@ali.muzaffar/what-is-android-os-fileuriexposedexception-and-what-you-can-do-about-it-70b9eb17c6d0

    Intent intent = new Intent(Intent.ACTION_VIEW);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(mFilePath));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("audio/*");
        intent.setDataAndType(uri, "audio/*");
    } else {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("audio/*");
        intent.setDataAndType(Uri.fromFile(new File(mFilePath)), "audio/*");
    }

    PendingIntent pendingIntent;
    pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(pendingIntent);
    Notification noti = mBuilder.build();
    noti.flags = Notification.FLAG_AUTO_CANCEL;
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(notifyID, noti);
}

From source file:com.orange.ocara.ui.activity.ListAuditActivity.java

@Receiver(actions = AuditExportService.EXPORT_SUCCESS, local = true, registerAt = Receiver.RegisterAt.OnResumeOnPause)
@UiThread(propagation = UiThread.Propagation.REUSE)
void onExportAuditDone(@Receiver.Extra String path) {
    setLoading(false);/*w  w w. ja va2s . co  m*/

    exportFile = new File(path);

    switch (exportAction) {
    case EXPORT_ACTION_SHARE: {

        // create an intent, so the user can choose which application he/she wants to use to share this file
        final Intent intent = ShareCompat.IntentBuilder.from(this)
                .setType(MimeTypeMap.getSingleton()
                        .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)))
                .setStream(FileProvider.getUriForFile(this, "com.orange.ocara", exportFile))
                .setChooserTitle("How do you want to share?").createChooserIntent()
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        startActivity(intent);
        break;
    }

    case EXPORT_ACTION_SAVE: {
        createNewDocument(path);
        break;
    }
    }
}

From source file:com.concavenp.artistrymuse.ImageAppCompatActivity.java

protected void dispatchTakePictureIntent() {

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

        // Create the File where the photo should go
        File photoFile = createImageFile();

        // Continue only if the File was successfully created
        if (photoFile != null) {

            Uri photoURI = FileProvider.getUriForFile(this, "com.concavenp.artistrymuse", photoFile);

            Log.d(TAG, "New camera image URI location: " + photoURI.toString());

            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

        }//from  ww w.  j  a va  2  s .  c o  m

    }

}

From source file:com.team.formal.eyeshopping.MainActivity.java

public void startCamera() {
    if (PermissionUtils.requestPermission(this, CAMERA_PERMISSIONS_REQUEST,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri = FileProvider.getUriForFile(getApplicationContext(),
                getApplicationContext().getPackageName() + ".provider", getCameraFile());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CAMERA_IMAGE_REQUEST);
    }// w w  w  .j  a  v  a 2s . c  o  m
}

From source file:org.telegram.ui.Components.ImageUpdater.java

public void openCamera() {
    if (parentFragment == null || parentFragment.getParentActivity() == null) {
        return;//from   w  w  w . j  a  v a2  s  .  c o  m
    }
    try {
        if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity()
                .checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            parentFragment.getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA },
                    19);
            return;
        }
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File image = AndroidUtilities.generatePicturePath();
        if (image != null) {
            if (Build.VERSION.SDK_INT >= 24) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(
                        parentFragment.getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image));
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
            }
            currentPicturePath = image.getAbsolutePath();
        }
        parentFragment.startActivityForResult(takePictureIntent, 13);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:com.android.settings.users.EditUserPhotoController.java

private Uri createTempImageUri(Context context, String fileName, boolean purge) {
    final File folder = context.getCacheDir();
    folder.mkdirs();//from  w w w. j  av a2  s . co  m
    final File fullPath = new File(folder, fileName);
    if (purge) {
        fullPath.delete();
    }
    return FileProvider.getUriForFile(context, RestrictedProfileSettings.FILE_PROVIDER_AUTHORITY, fullPath);
}

From source file:nuclei.ui.share.PackageTargetManager.java

protected void onSetFileProvider(Context context, String packageName, String authority, Intent intent) {
    if (mUri != null || mFile != null) {
        Uri uri = mUri;/*  w  ww .  j av a 2  s.c om*/
        String type = "*/*";
        if (mFile != null) {
            uri = FileProvider.getUriForFile(context, authority, mFile);
            final int lastDot = mFile.getName().lastIndexOf('.');
            if (lastDot >= 0) {
                String extension = mFile.getName().substring(lastDot + 1);
                String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (mimeType != null)
                    type = mimeType;
            }
        }
        intent.setDataAndType(intent.getData(), type);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        if (packageName != null) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    } else {
        intent.setType("text/plain");
    }
}

From source file:net.opendasharchive.openarchive.ReviewMediaActivity.java

private void showMedia() {

    if (mMedia.mimeType.startsWith("image")) {
        ArrayList<Uri> list = new ArrayList<>();
        list.add(Uri.parse(mMedia.getOriginalFilePath()));
        new ImageViewer.Builder(this, list).setStartPosition(0).show();
    } else {/* ww  w .  j a va2  s  . c om*/
        Intent viewMediaIntent = new Intent();
        viewMediaIntent.setAction(Intent.ACTION_VIEW);

        Uri uriFile = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",
                FileUtils.getFile(this, Uri.parse(mMedia.getOriginalFilePath())));

        viewMediaIntent.setDataAndType(uriFile, mMedia.getMimeType());
        viewMediaIntent.putExtra(Intent.EXTRA_STREAM, uriFile);
        viewMediaIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        startActivity(viewMediaIntent);
    }
}

From source file:com.brq.wallet.activity.export.BackupToPdfActivity.java

private Uri getUri() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        String authority = getFileProviderAuthority();
        return FileProvider.getUriForFile(this, authority, getFileStreamPath(getFullExportFilePath()));
    } else {/*from   w  ww.  j av a 2  s .  c o m*/
        return Uri.fromFile(new File(getFullExportFilePath()));
    }
}