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.luboganev.dejalist.ui.MainActivity.java

@Override
public void shareProduct(Product product) {
    if (product.uri != null) {
        Intent shareIntent = new Intent();
        String fileName = new File(Uri.parse(product.uri).getPath()).getName();
        File sharedFile = ProductImageFileHelper.getFile(this, fileName);
        Utils.d(this, sharedFile.toString());
        Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
                "com.luboganev.dejalist.productimagesprovider", sharedFile);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.dialog_share_product)));
    } else {// www .j  a  v a2  s .  c o  m
        Toast.makeText(getApplicationContext(), R.string.toast_no_image_to_share, Toast.LENGTH_SHORT).show();
    }
}

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

private void shareMedia() {

    StringBuffer sb = new StringBuffer();
    sb.append("\"").append(mMedia.getTitle()).append("\"").append(' ');
    sb.append(getString(R.string.share_media_text)).append(' ');
    sb.append(mMedia.getServerUrl());/*from www  .  j  a  va  2  s  .  c om*/

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType(mMedia.getMimeType());
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mMedia.getTitle());
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, sb.toString());

    Uri sharedFileUri = null;
    String mediaPath = mMedia.getOriginalFilePath();
    if (mediaPath.startsWith("content:"))
        sharedFileUri = Uri.parse(mediaPath);
    else
        sharedFileUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",
                new File(mMedia.getOriginalFilePath()));

    sharingIntent.putExtra(Intent.EXTRA_STREAM, sharedFileUri);

    startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));
}

From source file:com.gdpi.app.UpdateManager.java

/**
 * APK//from  w ww .j a  va  2  s  .  com
 */
private void installApk() {
    /**
     * android7.0
     */
    File apkfile = new File(mSavePath, name);
    if (!apkfile.exists()) {
        return;
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    // Activity?Activity,?
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= N) { //?7.0
        //?1 , ?2 Provider? ???   ?3  
        Uri apkUri = FileProvider.getUriForFile(mContext, "com.gpdi.app.fileprovider", apkfile);
        //??Uri
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
    }
    mContext.startActivity(intent);
    android.os.Process.killProcess(android.os.Process.myPid());

}

From source file:org.rm3l.ddwrt.tiles.admin.nvram.AdminNVRAMTile.java

private void setShareFile(File file) {
    if (mShareActionProvider == null) {
        return;/* w ww. j  a va2s. com*/
    }

    final Uri uriForFile = FileProvider.getUriForFile(mParentFragmentActivity, "org.rm3l.fileprovider", file);

    mShareActionProvider
            .setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener() {
                @Override
                public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
                    mParentFragmentActivity.grantUriPermission(intent.getComponent().getPackageName(),
                            uriForFile, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    return true;
                }
            });

    final Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, uriForFile);
    if (mRouter != null) {
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("NVRAM Variables dump from router '%s' (%s)",
                mRouter.getName(), mRouter.getRemoteIpAddress()));
    }
    sendIntent.setData(uriForFile);
    sendIntent.setType("text/plain");
    sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    setShareIntent(sendIntent);

}

From source file:fpt.isc.nshreport.utilities.FileUtils.java

public static Uri createImageFile(Context context) throws IOException {
    // Create an image file name
    /*String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";*/
    String imageFileName = "JPEG_NSH.jpg";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "Camera");
    /*File image = File.createTempFile(
        imageFileName,  *//* prefix *//*
                                       ".jpg",         *//* suffix *//*
                                                                      storageDir      *//* directory *//*
                                                                                                        );*/

    File image = new File(storageDir, imageFileName);

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Uri photoURI = FileProvider.getUriForFile(context, "fpt.isc.nshreport.provider", image);
    return photoURI;
}

From source file:com.metinkale.prayerapp.vakit.fragments.MainFragment.java

private void export(int csvpdf, LocalDate from, LocalDate to) throws IOException {
    File outputDir = getActivity().getCacheDir();
    if (!outputDir.exists())
        outputDir.mkdirs();//from ww w  .  ja v a2  s.c  om
    File outputFile = new File(outputDir, mTimes.getName().replace(" ", "_") + (csvpdf == 0 ? ".csv" : ".pdf"));
    if (outputDir.exists())
        outputFile.delete();
    FileOutputStream outputStream;

    outputStream = new FileOutputStream(outputFile);
    if (csvpdf == 0) {
        outputStream.write("Date;Fajr;Shuruq;Dhuhr;Asr;Maghrib;Ishaa\n".getBytes());

        do {
            outputStream.write((from.toString("yyyy-MM-dd") + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 0) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 1) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 2) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 3) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 4) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 5) + "\n").getBytes());
        } while (!(from = from.plusDays(1)).isAfter(to));
        outputStream.close();

    } else {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            PdfDocument document = new PdfDocument();

            PdfDocument.PageInfo pageInfo = null;
            int pw = 595;
            int ph = 842;
            pageInfo = new PdfDocument.PageInfo.Builder(pw, ph, 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            Drawable launcher = Drawable.createFromStream(getActivity().getAssets().open("pdf/launcher.png"),
                    null);
            Drawable qr = Drawable.createFromStream(getActivity().getAssets().open("pdf/qrcode.png"), null);
            Drawable badge = Drawable.createFromStream(
                    getActivity().getAssets().open("pdf/badge_" + Prefs.getLanguage() + ".png"), null);

            launcher.setBounds(30, 30, 30 + 65, 30 + 65);
            qr.setBounds(pw - 30 - 65, 30 + 65 + 5, pw - 30, 30 + 65 + 5 + 65);
            int w = 100;
            int h = w * badge.getIntrinsicHeight() / badge.getIntrinsicWidth();
            badge.setBounds(pw - 30 - w, 30 + (60 / 2 - h / 2), pw - 30, 30 + (60 / 2 - h / 2) + h);

            Canvas canvas = page.getCanvas();

            Paint paint = new Paint();
            paint.setARGB(255, 0, 0, 0);
            paint.setTextSize(10);
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("com.metinkale.prayer", pw - 30 - w / 2, 30 + (60 / 2 - h / 2) + h + 10, paint);

            launcher.draw(canvas);
            qr.draw(canvas);
            badge.draw(canvas);

            paint.setARGB(255, 61, 184, 230);
            canvas.drawRect(30, 30 + 60, pw - 30, 30 + 60 + 5, paint);

            if (mTimes.getSource().resId != 0) {
                Drawable source = getResources().getDrawable(mTimes.getSource().resId);

                h = 65;
                w = h * source.getIntrinsicWidth() / source.getIntrinsicHeight();
                source.setBounds(30, 30 + 65 + 5, 30 + w, 30 + 65 + 5 + h);
                source.draw(canvas);
            }

            paint.setARGB(255, 0, 0, 0);
            paint.setTextSize(40);
            paint.setTextAlign(Paint.Align.LEFT);
            canvas.drawText(getText(R.string.appName).toString(), 30 + 65 + 5, 30 + 50, paint);
            paint.setTextAlign(Paint.Align.CENTER);
            paint.setFakeBoldText(true);
            canvas.drawText(mTimes.getName(), pw / 2.0f, 30 + 65 + 50, paint);

            paint.setTextSize(12);
            int y = 30 + 65 + 5 + 65 + 30;
            int p = 30;
            int cw = (pw - p - p) / 7;
            canvas.drawText(getString(R.string.date), 30 + (0.5f * cw), y, paint);
            canvas.drawText(Vakit.IMSAK.getString(), 30 + (1.5f * cw), y, paint);
            canvas.drawText(Vakit.GUNES.getString(), 30 + (2.5f * cw), y, paint);
            canvas.drawText(Vakit.OGLE.getString(), 30 + (3.5f * cw), y, paint);
            canvas.drawText(Vakit.IKINDI.getString(), 30 + (4.5f * cw), y, paint);
            canvas.drawText(Vakit.AKSAM.getString(), 30 + (5.5f * cw), y, paint);
            canvas.drawText(Vakit.YATSI.getString(), 30 + (6.5f * cw), y, paint);
            paint.setFakeBoldText(false);
            do {
                y += 20;
                canvas.drawText((from.toString("dd.MM.yyyy")), 30 + (0.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 0)), 30 + (1.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 1)), 30 + (2.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 2)), 30 + (3.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 3)), 30 + (4.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 4)), 30 + (5.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 5)), 30 + (6.5f * cw), y, paint);
            } while (!(from = from.plusDays(1)).isAfter(to));
            document.finishPage(page);

            document.writeTo(outputStream);

            // close the document
            document.close();

        } else {
            Toast.makeText(getActivity(), R.string.versionNotSupported, Toast.LENGTH_LONG).show();
        }
    }

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType(csvpdf == 0 ? "text/csv" : "application/pdf");

    Uri uri = FileProvider.getUriForFile(getActivity(), "com.metinkale.prayer.fileprovider", outputFile);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.export)));
}

From source file:com.android.nfc.beam.BeamTransferManager.java

Intent buildViewIntent() {
    if (mPaths.size() == 0)
        return null;

    Intent viewIntent = new Intent(Intent.ACTION_VIEW);

    String filePath = mPaths.get(0);
    Uri mediaUri = mMediaUris.get(filePath);
    Uri uri = mediaUri != null ? mediaUri
            : FileProvider.getUriForFile(mContext, "com.google.android.nfc.fileprovider", new File(filePath));
    viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath));
    viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    return viewIntent;
}

From source file:com.lastsoft.plog.adapter.GameAdapter.java

public void playPopup(View v, final int position) {

    try {/*from w w w.ja v a 2  s. c  om*/
        InputMethodManager inputManager = (InputMethodManager) mActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception ignored) {
    }

    PopupMenu popup = new PopupMenu(mActivity, v);

    MenuInflater inflater = popup.getMenuInflater();

    if (games.get(position).expansionFlag == true) {
        inflater.inflate(R.menu.game_expansion_overflow, popup.getMenu());
    } else {
        inflater.inflate(R.menu.game_overflow, popup.getMenu());
    }
    if (games.get(position).gameBGGID == null || games.get(position).gameBGGID.equals("")) {
        popup.getMenu().removeItem(R.id.update_bgg);
        popup.getMenu().removeItem(R.id.open_bgg);
        popup.getMenu().removeItem(R.id.add_bgg);
    }
    if (games.get(position).gameBoxImage == null || games.get(position).gameBoxImage.equals("")) {
        popup.getMenu().removeItem(R.id.view_box_photo);
    }
    if (games.get(position).taggedToPlay <= 0) {
        popup.getMenu().removeItem(R.id.remove_bucket_list);
    } else {
        popup.getMenu().removeItem(R.id.add_bucket_list);
    }

    SharedPreferences app_preferences;
    app_preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);
    long currentDefaultPlayer = app_preferences.getLong("defaultPlayer", -1);
    if (games.get(position).collectionFlag || currentDefaultPlayer == -1) {
        popup.getMenu().removeItem(R.id.add_bgg);
    }

    //check if this game has been played
    //if so, can't delete
    if (GamesPerPlay.hasGameBeenPlayed(games.get(position))) {
        popup.getMenu().removeItem(R.id.delete_game);
    }
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.delete_game:
                ((MainActivity) mActivity).deleteGame(games.get(position).getId());
                return true;
            case R.id.add_tenbyten:
                ((MainActivity) mActivity).addToTenXTen(games.get(position).getId());
                return true;
            case R.id.view_plays:
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 9, fragmentName,
                            currentYear);
                } else {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 0, fragmentName,
                            currentYear);
                }
                return true;
            case R.id.open_bgg:
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://bgg.cc/boardgame/" + games.get(position).gameBGGID));
                mActivity.startActivity(browserIntent);
                return true;
            case R.id.update_bgg:
                mPosition = position;
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, true, -1);
                } else {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, false, -1);
                }
                return true;
            case R.id.add_bgg:
                mPosition = position;
                ((MainActivity) mActivity).updateGameViaBGG(games.get(position).gameName,
                        games.get(position).gameBGGID, "", true, false);
                return true;
            case R.id.add_box_photo:
                ((GamesFragment) mFragment).captureBox(games.get(position));
                return true;
            case R.id.view_box_photo:
                String[] photoParts = games.get(position).gameBoxImage.split("/");
                File newFile = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                                + "/Plog/",
                        photoParts[photoParts.length - 1]);
                Uri contentUri = FileProvider.getUriForFile(mActivity.getApplicationContext(),
                        "com.lastsoft.plog.fileprovider", newFile);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(contentUri, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mActivity.startActivity(intent);
                return true;
            case R.id.add_bucket_list:
                String[] ids = TimeZone.getAvailableIDs(-5 * 60 * 60 * 1000);
                // if no ids were returned, something is wrong. get out.
                //if (ids.length == 0)
                //    System.exit(0);

                // begin output
                //System.out.println("Current Time");

                // create a Eastern Standard Time time zone
                SimpleTimeZone pdt = new SimpleTimeZone(-5 * 60 * 60 * 1000, ids[0]);

                // set up rules for daylight savings time
                pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
                pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

                // create a GregorianCalendar with the Pacific Daylight time zone
                // and the current date and time
                Calendar calendar = new GregorianCalendar(pdt);
                Date trialTime = new Date();
                calendar.setTime(trialTime);
                int i = (int) (calendar.getTime().getTime() / 1000);
                games.get(position).taggedToPlay = i;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.added_to_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                games.get(position).taggedToPlay = 0;
                                games.get(position).save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!

                return true;
            case R.id.remove_bucket_list:
                final int taggedToPlay = games.get(position).taggedToPlay;
                final Game gameToUndo = games.get(position);
                games.get(position).taggedToPlay = 0;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.removed_from_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                gameToUndo.taggedToPlay = taggedToPlay;
                                gameToUndo.save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!
                if (playListType == 2) {
                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                }
                return true;
            default:
                return false;
            }
        }
    }

    );
    popup.show();
}

From source file:org.gnucash.android.export.ExportAsyncTask.java

/**
 * Convert file paths to URIs by adding the file// prefix
 * <p>e.g. /some/path/file.ext --> file:///some/path/file.ext</p>
 * @param paths List of file paths to convert
 * @return List of file URIs/*from  w w  w .  j  a  va2s .  c  om*/
 */
@NonNull
private ArrayList<Uri> convertFilePathsToUris(List<String> paths) {
    ArrayList<Uri> exportFiles = new ArrayList<>();

    for (String path : paths) {
        File file = new File(path);
        Uri contentUri = FileProvider.getUriForFile(GnuCashApplication.getAppContext(),
                GnuCashApplication.FILE_PROVIDER_AUTHORITY, file);
        exportFiles.add(contentUri);
    }
    return exportFiles;
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * This plugin also has P2P functionality with others. It provides generic way to
 * read and write tags for the file.//from w w  w .  j  a v  a2s  . c  om
 * <br/>
 * If intent is passed with EXTRA_PARAM_P2P and READ then EXTRA_PARAM_P2P_KEY is considered
 * as an array of field keys to retrieve from file. The values read are written in the same order
 * into answer intent into EXTRA_PARAM_P2P_VAL.
 * <br/>
 * If intent is passed with EXTRA_PARAM_P2P and WRITE then EXTRA_PARAM_P2P_KEY is considered
 * as an array of field keys to write to file. EXTRA_PARAM_P2P_VAL represents values to be written in
 * the same order.
 *
 */
private void handleP2pIntent() {
    String request = mLaunchIntent.getStringExtra(EXTRA_PARAM_P2P);
    switch (request) {
    case P2P_WRITE_TAG: {
        String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY);
        String[] values = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_VAL);
        for (int i = 0; i < fields.length; ++i) {
            try {
                FieldKey key = FieldKey.valueOf(fields[i]);
                mTag.setField(key, values[i]);
            } catch (IllegalArgumentException iae) {
                Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae);
                Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show();
            } catch (FieldDataInvalidException e) {
                // should not happen
                Log.e(LOG_TAG, "Error writing tag", e);
            }
        }
        writeFile();
        break;
    }
    case P2P_READ_TAG: {
        String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY);
        ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP);

        String[] values = new String[fields.length];
        for (int i = 0; i < fields.length; ++i) {
            try {
                FieldKey key = FieldKey.valueOf(fields[i]);
                values[i] = mTag.getFirst(key);
            } catch (IllegalArgumentException iae) {
                Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae);
                Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show();
            }
        }

        Intent response = new Intent(ACTION_LAUNCH_PLUGIN);
        response.putExtra(EXTRA_PARAM_P2P, P2P_READ_TAG);
        response.setPackage(responseApp.packageName);
        response.putExtra(EXTRA_PARAM_P2P_VAL, values);
        startService(response);
        break;
    }
    case P2P_READ_ART: {
        ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP);
        Artwork cover = mTag.getFirstArtwork();
        Uri uri = null;
        try {
            if (cover == null) {
                Log.w(LOG_TAG, "Artwork is not present for file " + mAudioFile.getFile().getName());
                break;
            }

            File coversDir = new File(getCacheDir(), "covers");
            if (!coversDir.exists() && !coversDir.mkdir()) {
                Log.e(LOG_TAG, "Couldn't create dir for covers! Path " + getCacheDir());
                break;
            }

            // cleanup old images
            for (File oldImg : coversDir.listFiles()) {
                if (!oldImg.delete()) {
                    Log.w(LOG_TAG, "Couldn't delete old image file! Path " + oldImg);
                }
            }

            // write artwork to file
            File coverTmpFile = new File(coversDir, UUID.randomUUID().toString());
            FileOutputStream fos = new FileOutputStream(coverTmpFile);
            fos.write(cover.getBinaryData());
            fos.close();

            // create sharable uri
            uri = FileProvider.getUriForFile(this, "com.kanedias.vanilla.audiotag.fileprovider", coverTmpFile);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Couldn't write to cache file", e);
            Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            // share uri if created successfully
            Intent response = new Intent(ACTION_LAUNCH_PLUGIN);
            response.putExtra(EXTRA_PARAM_P2P, P2P_READ_ART);
            response.setPackage(responseApp.packageName);
            if (uri != null) {
                grantUriPermission(responseApp.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                response.putExtra(EXTRA_PARAM_P2P_VAL, uri);
            }
            startService(response);
        }
        break;
    }
    case P2P_WRITE_ART: {
        Uri imgLink = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_P2P_VAL);

        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imgLink, "r");
            if (pfd == null) {
                return;
            }

            FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
            byte[] imgBytes = TagEditorUtils.readFully(fis);

            Artwork cover = new AndroidArtwork();
            cover.setBinaryData(imgBytes);
            cover.setMimeType(ImageFormats.getMimeTypeForBinarySignature(imgBytes));
            cover.setDescription("");
            cover.setPictureType(PictureTypes.DEFAULT_ID);

            mTag.deleteArtworkField();
            mTag.setField(cover);
        } catch (IOException | IllegalArgumentException | FieldDataInvalidException e) {
            Log.e(LOG_TAG, "Invalid artwork!", e);
            Toast.makeText(this, R.string.invalid_artwork_provided, Toast.LENGTH_SHORT).show();
        }

        writeFile();
        break;
    }
    }

}