Example usage for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

Introduction

In this page you can find the example usage for android.content Intent FLAG_GRANT_READ_URI_PERMISSION.

Prototype

int FLAG_GRANT_READ_URI_PERMISSION

To view the source code for android.content Intent FLAG_GRANT_READ_URI_PERMISSION.

Click Source Link

Document

If set, the recipient of this Intent will be granted permission to perform read operations on the URI in the Intent's data and any URIs specified in its ClipData.

Usage

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

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

    try {/*from  w  w  w .ja  v a2s .  co  m*/
        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:cz.maresmar.sfm.service.plugin.sync.SyncHandler.java

private void startPlugin(@NonNull String plugin, long portalId, long credentialsID, @SyncTask int pluginTasks) {
    Intent intent = PluginUtils.buildPluginIntent(plugin);

    // Puts action details
    intent.setAction(ActionContract.ACTION_SYNC);
    intent.putExtra(ActionContract.EXTRA_PORTAL_ID, portalId);
    intent.putExtra(ActionContract.EXTRA_CREDENTIAL_ID, credentialsID);
    intent.putExtra(ActionContract.EXTRA_TASKS, pluginTasks);

    // Provides access to login data
    intent.setData(LogData.getUri(portalId, credentialsID));

    // Give permissions to access data
    int rwFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

    String packageName = intent.getComponent().getPackageName();
    mContext.grantUriPermission(packageName, intent.getData(), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.Action.getCredentialUri(credentialsID), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.GroupMenuEntry.getPortalUri(portalId), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.MenuEntry.getPortalUri(portalId), rwFlags);

    Timber.i("Starting plugin \"%s\" on portal %d with credential %d", plugin, portalId, credentialsID);
    // Fire start
    PluginUtils.startPlugin(mContext, intent);
}

From source file:com.owncloud.android.ui.preview.PreviewMediaFragment.java

/**
 * Opens the previewed file with an external application.
 * //from   w w w. ja  v  a2s  .  c o  m
 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server, 
 * we should get a list of available apps for MIME tpye in the server and join it with the list of 
 * available apps for the MIME type known from the file extension, to let the user choose
 */
private void openFile() {
    stopPreview(true);
    String storagePath = mFile.getStoragePath();
    String encodedStoragePath = WebdavUtils.encodePath(storagePath);
    try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
        i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(i);

    } catch (Throwable t) {
        Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: "
                + mFile.getMimetype());
        boolean toastIt = true;
        String mimeType = "";
        try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
                if (mimeType != null) {
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                } else {
                    // desperate try
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), "*-/*");
                }
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(i);
                toastIt = false;
            }

        } catch (IndexOutOfBoundsException e) {
            Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType
                    + " obtained from extension");

        } catch (Throwable th) {
            Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

        } finally {
            if (toastIt) {
                Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(),
                        Toast.LENGTH_SHORT).show();
            }
        }

    }
    finish();
}

From source file:org.uoyabause.android.tv.GameSelectFragment.java

private void updateBackGraound() {

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String image_path = sp.getString("select_image", "err");
    if (image_path.equals("err")) {
        mDefaultBackground = getResources().getDrawable(R.drawable.saturn);
        mBackgroundManager.setDrawable(mDefaultBackground);
    } else {// w w w . j ava  2  s .  c o m
        try {

            getActivity().grantUriPermission("org.uoyabause.android", Uri.parse(image_path),
                    Intent.FLAG_GRANT_READ_URI_PERMISSION);

            InputStream inputStream = getActivity().getContentResolver().openInputStream(Uri.parse(image_path));

            BitmapFactory.Options imageOptions = new BitmapFactory.Options();
            imageOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(inputStream, null, imageOptions);
            Log.v("image", "Original Image Size: " + imageOptions.outWidth + " x " + imageOptions.outHeight);

            inputStream.close();

            Bitmap bitmap;
            int imageSizeMax = 1920;
            inputStream = getActivity().getContentResolver().openInputStream(Uri.parse(image_path));
            float imageScaleWidth = (float) imageOptions.outWidth / imageSizeMax;
            float imageScaleHeight = (float) imageOptions.outHeight / imageSizeMax;

            if (imageScaleWidth > 2 && imageScaleHeight > 2) {
                BitmapFactory.Options imageOptions2 = new BitmapFactory.Options();
                int imageScale = (int) Math
                        .floor((imageScaleWidth > imageScaleHeight ? imageScaleHeight : imageScaleWidth));
                for (int i = 2; i <= imageScale; i *= 2) {
                    imageOptions2.inSampleSize = i;
                }
                bitmap = BitmapFactory.decodeStream(inputStream, null, imageOptions2);
                Log.v("image", "Sample Size: 1/" + imageOptions2.inSampleSize);
            } else {
                bitmap = BitmapFactory.decodeStream(inputStream);
            }

            inputStream.close();
            //mDefaultBackground = Drawable.createFromStream(inputStream, image_path );
            mBackgroundManager.setBitmap(bitmap);

        } catch (Exception e) {
            mDefaultBackground = getResources().getDrawable(R.drawable.saturn);
            mBackgroundManager.setDrawable(mDefaultBackground);
        }

    }

}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openWith(final DocumentFile f, final Context c) {
    MaterialDialog.Builder a = new MaterialDialog.Builder(c);
    a.title(c.getResources().getString(R.string.openas));
    String[] items = new String[] { c.getResources().getString(R.string.text),
            c.getResources().getString(R.string.image), c.getResources().getString(R.string.video),
            c.getResources().getString(R.string.audio), c.getResources().getString(R.string.database),
            c.getResources().getString(R.string.other) };

    a.items(items).itemsCallback(new MaterialDialog.ListCallback() {
        @Override//from ww w .  j  a  v  a2  s  .com
        public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) {

            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            switch (i) {
            case 0:
                intent.setDataAndType(f.getUri(), "text/*");
                break;
            case 1:
                intent.setDataAndType(f.getUri(), "image/*");
                break;
            case 2:
                intent.setDataAndType(f.getUri(), "video/*");
                break;
            case 3:
                intent.setDataAndType(f.getUri(), "audio/*");
                break;
            case 4:
                intent = new Intent(c, DbViewer.class);
                intent.putExtra("path", f.getUri());
                break;
            case 5:
                intent.setDataAndType(f.getUri(), "*/*");
                break;
            }
            try {
                c.startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
                openWith(f, c);
            }
        }
    });
    try {
        a.build().show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  www  .jav  a2s . c o m
 * <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;
    }
    }

}

From source file:org.mariotaku.twidere.activity.MediaViewerActivity.java

protected void shareMedia() {
    if (mShareMediaPosition == -1)
        return;//from  w  w w.  j  ava 2s . co  m
    final ViewPager viewPager = findViewPager();
    final PagerAdapter adapter = viewPager.getAdapter();
    final Object object = adapter.instantiateItem(viewPager, mShareMediaPosition);
    if (!(object instanceof CacheDownloadMediaViewerFragment))
        return;
    CacheDownloadLoader.Result result = ((CacheDownloadMediaViewerFragment) object).getDownloadResult();
    if (result == null || result.cacheUri == null) {
        // TODO show error
        return;
    }
    final File destination = ShareProvider.getFilesDir(this);
    if (destination == null)
        return;
    String type;
    if (object instanceof VideoPageFragment) {
        type = CacheProvider.Type.VIDEO;
    } else if (object instanceof ImagePageFragment) {
        type = CacheProvider.Type.IMAGE;
    } else if (object instanceof GifPageFragment) {
        type = CacheProvider.Type.IMAGE;
    } else {
        throw new UnsupportedOperationException("Unsupported fragment " + object);
    }
    final SaveFileTask task = new SaveFileTask(this, result.cacheUri, destination,
            new CacheProvider.CacheFileTypeCallback(this, type)) {
        private static final String PROGRESS_FRAGMENT_TAG = "progress";

        @Override
        protected void dismissProgress() {
            final IExtendedActivity activity = (IExtendedActivity) getContext();
            if (activity == null)
                return;
            activity.executeAfterFragmentResumed(new IExtendedActivity.Action() {
                @Override
                public void execute(IExtendedActivity activity) {
                    final FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
                    final DialogFragment fragment = (DialogFragment) fm
                            .findFragmentByTag(PROGRESS_FRAGMENT_TAG);
                    if (fragment != null) {
                        fragment.dismiss();
                    }
                }
            });
        }

        @Override
        protected void showProgress() {
            final IExtendedActivity activity = (IExtendedActivity) getContext();
            if (activity == null)
                return;
            activity.executeAfterFragmentResumed(new IExtendedActivity.Action() {
                @Override
                public void execute(IExtendedActivity activity) {
                    final DialogFragment fragment = new ProgressDialogFragment();
                    fragment.setCancelable(false);
                    fragment.show(((FragmentActivity) activity).getSupportFragmentManager(),
                            PROGRESS_FRAGMENT_TAG);
                }
            });
        }

        @Override
        protected void onFileSaved(@NonNull File savedFile, @Nullable String mimeType) {
            final MediaViewerActivity activity = (MediaViewerActivity) getContext();
            if (activity == null)
                return;

            final Uri fileUri = ShareProvider.getUriForFile(activity, AUTHORITY_TWIDERE_SHARE, savedFile);

            final Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setDataAndType(fileUri, mimeType);
            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent.addFlags(Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
            }
            activity.processShareIntent(intent);
            startActivityForResult(Intent.createChooser(intent, activity.getString(R.string.share)),
                    REQUEST_SHARE_MEDIA);
        }

        @Override
        protected void onFileSaveFailed() {
            final MediaViewerActivity activity = (MediaViewerActivity) getContext();
            if (activity == null)
                return;
            Toast.makeText(activity, R.string.error_occurred, Toast.LENGTH_SHORT).show();
        }
    };
    AsyncTaskUtils.executeTask(task);
}

From source file:com.mediatek.galleryfeature.stereo.segment.background.StereoBackgroundActivity.java

private void setupMenu() {
    if (mMenu == null || mMasterImage == null) {
        return;// w w  w. j  a v  a  2 s  .c o  m
    }

    mMenuRefineOriginal = mMenu.findItem(R.id.refine_refine_foreground);
    mMenuRefineOriginal.setVisible(true);

    mMenuRefineOriginal.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            Intent intent = new Intent("action_stereo_pick");
            intent.setDataAndType(getIntent().getData(), getIntent().getType())
                    .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            if (mMaskSimulator != null) {
                mMaskSimulator.release();
                mMaskSimulator = null;
            }

            startActivityForResult(intent, REQUEST_CODE_REFINE);

            return false;
        }
    });
}

From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == RESULT_CHOOSE_DIRECTORY) {
            Uri uriTree = data.getData();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    getActivity().getContentResolver().takePersistableUriPermission(uriTree,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                } catch (SecurityException e) {
                    e.printStackTrace();
                }// w w w .ja  va  2s.  c  o  m
            }
            String path = uriTree.toString();
            String displayPath = Uri.decode(path);
            SharedPreferencesUtil.saveData(getActivity(), KEY_PREF_DOWNLOAD_PATH, path);
            getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath);
        }
    }
}

From source file:com.mycelium.wallet.activity.modern.ModernMain.java

private void shareTransactionHistory() {
    WalletAccount account = _mbwManager.getSelectedAccount();
    MetadataStorage metaData = _mbwManager.getMetadataStorage();
    try {//  w w w. ja  v  a2s. c  om
        String fileName = "MyceliumExport_" + System.currentTimeMillis() + ".csv";
        File historyData = DataExport.getTxHistoryCsv(account, metaData, getFileStreamPath(fileName));
        PackageManager packageManager = Preconditions.checkNotNull(getPackageManager());
        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_PROVIDERS);
        for (ProviderInfo info : packageInfo.providers) {
            if (info.name.equals("android.support.v4.content.FileProvider")) {
                String authority = info.authority;
                Uri uri = FileProvider.getUriForFile(this, authority, historyData);
                Intent intent = ShareCompat.IntentBuilder.from(this).setStream(uri) // uri from FileProvider
                        .setType("text/plain")
                        .setSubject(getResources().getString(R.string.transaction_history_title))
                        .setText(getResources().getString(R.string.transaction_history_title)).getIntent()
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                startActivity(Intent.createChooser(intent,
                        getResources().getString(R.string.share_transaction_history)));
            }
        }
    } catch (IOException | PackageManager.NameNotFoundException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    }
}