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.stfalcon.contentmanager.ContentManager.java

/**
 * Pick image or video content from storage or google acc
 *
 * @param content image or video/*from  w  w  w . j ava 2  s .c  om*/
 */
public void pickContent(Content content) {
    savedTask = CONTENT_PICKER;
    savedContent = content;
    if (isStoragePermissionGranted(activity, fragment)) {
        this.targetFile = createFile(content);
        if (Build.VERSION.SDK_INT < 19) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType(content.toString());
            if (fragment == null) {
                activity.startActivityForResult(photoPickerIntent, CONTENT_PICKER);
            } else {
                fragment.startActivityForResult(photoPickerIntent, CONTENT_PICKER);
            }
        } else {
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType(content.toString());
            photoPickerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
            if (photoPickerIntent.resolveActivity(activity.getPackageManager()) != null) {
                if (fragment == null) {
                    activity.startActivityForResult(photoPickerIntent, CONTENT_PICKER);
                } else {
                    fragment.startActivityForResult(photoPickerIntent, CONTENT_PICKER);
                }
            }
        }
    }
}

From source file:com.slim.turboeditor.activity.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_FILE_CODE) {

            final Uri data = intent.getData();
            File newFile = new File(data.getPath());

            newFileToOpen(newFile, "");
        } else {//from ww  w  .  j a v  a2s  . c o m

            final Uri data = intent.getData();
            final File newFile = new File(data.getPath());

            // grantUriPermission(getPackageName(),
            // data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(data,
                    (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));

            if (requestCode == READ_REQUEST_CODE || requestCode == CREATE_REQUEST_CODE) {

                newFileToOpen(newFile, "");
            }

            if (requestCode == SAVE_AS_REQUEST_CODE) {
                getSaveFileObservable(getApplicationContext(), newFile,
                        pageSystem.getAllText(mEditor.getText().toString()), currentEncoding)
                                .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        savedAFile(aBoolean);
                                        newFileToOpen(newFile, "");
                                    }
                                });
            }
        }
    }
}

From source file:com.xperia64.timidityae.SettingsActivity.java

@SuppressLint("NewApi")
@Override//  www.  ja  v a  2 s  . com
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == 42) {
        if (resultCode == RESULT_OK) {
            Uri treeUri = data.getData();
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Globals.theFold = treeUri;
        } else {
            Globals.theFold = null;
        }

    }
}

From source file:org.thezero.qrfi.SuperAwesomeCardFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView;
    if (position == 0) {
        rootView = inflater.inflate(R.layout.fragment_generate, container, false);
        final CardView cardQr = (CardView) rootView.findViewById(R.id.card_qr);
        cardQr.setVisibility(View.GONE);

        String[] items = new String[] { "Open", "WEP", "WPA/WPA2" };
        final EditText ssid = (EditText) rootView.findViewById(R.id.edit_ssid);
        final EditText pass = (EditText) rootView.findViewById(R.id.edit_pass);
        final Spinner spinner = (Spinner) rootView.findViewById(R.id.wifi_type);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(c, android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);/* ww  w .j  av  a  2s . c  o  m*/
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getSelectedItem().toString().equals("Open")) {
                    rootView.findViewById(R.id.second).setVisibility(View.GONE);
                } else {
                    rootView.findViewById(R.id.second).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        final boolean[] cardHide = { true };
        Button delete = (Button) rootView.findViewById(R.id.delete);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardHide[0] = true;
                cardQr.animate().translationY(0).alpha(0.0f).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        if (cardHide[0])
                            cardQr.setVisibility(View.GONE);
                    }
                });
                ssid.setText("");
                pass.setText("");
                spinner.setSelection(0);
            }
        });

        Button gen = (Button) rootView.findViewById(R.id.generate);
        gen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // WIFI:S:Pistol;T:WEP;P:pistolawifi2;;
                if (pass.getText().length() < 8 && !spinner.getSelectedItem().toString().equals("Open")) {
                    Toast.makeText(c, c.getString(R.string.error_pass), Toast.LENGTH_LONG).show();
                    return;
                }
                String ap = "WIFI:S:" + ssid.getText() + ";T:" + spinner.getSelectedItem().toString() + ";P:"
                        + pass.getText() + ";;";
                Log.d(TAG, ap);
                QRCodeWriter writer = new QRCodeWriter();
                try {
                    BitMatrix matrix = writer.encode(ap, BarcodeFormat.QR_CODE, 700, 700, null);
                    int height = matrix.getHeight();
                    int width = matrix.getWidth();
                    final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                    for (int x = 0; x < width; x++) {
                        for (int y = 0; y < height; y++) {
                            bmp.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE);
                        }
                    }
                    ImageView qr_image = (ImageView) rootView.findViewById(R.id.qrimage);
                    qr_image.setImageBitmap(bmp);
                    cardHide[0] = false;
                    cardQr.setVisibility(View.VISIBLE);
                    cardQr.setAlpha(1.0f);
                    cardQr.animate().translationY(10).alpha(1.0f);

                    Button dialogButton = (Button) rootView.findViewById(R.id.ok);
                    dialogButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            File sdcard = Environment.getExternalStorageDirectory();
                            FileOutputStream out = null;
                            File check = new File(sdcard, "/wifipv/");
                            if (!(check.exists())) {
                                boolean resu = check.mkdir();
                                if (!resu) {
                                    return;
                                }
                            }

                            try {
                                File myFile = new File(sdcard, "/wifipv/" + ssid.getText() + ".png");
                                out = new FileOutputStream(myFile);
                                boolean success = bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
                                if (success) {
                                    MediaScannerConnection.scanFile(c,
                                            new String[] { myFile.getAbsolutePath() }, null,
                                            new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Log.d(TAG, "file " + path + " was scanned seccessfully: "
                                                            + uri);
                                                    Intent shareIntent = new Intent();
                                                    shareIntent.setAction(Intent.ACTION_SEND);
                                                    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                                                    shareIntent.setType("image/png");
                                                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                                    Intent new_intent = Intent.createChooser(shareIntent,
                                                            c.getText(R.string.send_to));
                                                    new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    c.startActivity(new_intent);

                                                }
                                            });
                                } else {
                                    Toast.makeText(c, c.getString(R.string.error_share), Toast.LENGTH_LONG)
                                            .show();
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } finally {
                                if (out != null)
                                    try {
                                        out.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                            }
                        }
                    });
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
        });
    } else {
        rootView = inflater.inflate(R.layout.fragment_scan, container, false);
        Button scan = (Button) rootView.findViewById(R.id.scan);
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(c, ScanActivity.class);
                myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                c.startActivity(myIntent);
            }
        });
        Button gallery = (Button) rootView.findViewById(R.id.gallery);
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFromGallery();
            }
        });
        /*final boolean[] tutorialHide = {false};
        final CardView tutorial = (CardView)rootView.findViewById(R.id.card_tutorial);
        tutorial.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                
            if(tutorialHide[0]){
                tutorialHide[0]=false;
                Animation anidelta = new ResizeAnimation(tutorial, tutorial.getHeight());
                anidelta.setDuration(500);
                anidelta.setFillAfter(true);
                tutorial.startAnimation(anidelta);
            }else{
                tutorialHide[0]=true;
                Animation anidelta = new ResizeAnimation(tutorial, 120);
                anidelta.setDuration(500);
                anidelta.setFillAfter(true);
                tutorial.startAnimation(anidelta);
            }
        }
        });*/
    }
    ViewCompat.setElevation(rootView, 50);
    return rootView;
}

From source file:com.example.zayankovsky.homework.ui.ImageDetailActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.save:
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {//from   w ww.j  av  a2  s .  c  o  m
            saveImageToGallery();
        }
        return true;
    case R.id.browser:
        Uri webpage = Uri.parse(FotkiWorker.getUrl());
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
            return true;
        }
        return false;
    case R.id.open:
        Uri imageUri = getUriForImage();
        if (imageUri == null) {
            return false;
        }

        Intent openIntent = new Intent();
        openIntent.setAction(Intent.ACTION_VIEW);
        // Put the Uri and MIME type in the result Intent
        openIntent.setDataAndType(imageUri, getContentResolver().getType(imageUri));
        // Grant temporary read permission to the content URI
        openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(openIntent);
        return true;
    case R.id.share:
        imageUri = getUriForImage();
        if (imageUri == null) {
            return false;
        }

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        // Put the Uri and MIME type in the result Intent
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType(getContentResolver().getType(imageUri));
        // Grant temporary read permission to the content URI
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, null));
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:com.doctoror.fuckoffmusicplayer.presentation.media.browser.MediaBrowserImpl.java

@NonNull
private MediaItem createMediaItemAlbum(@NonNull final Cursor c) {
    final MediaDescriptionCompat.Builder description = new MediaDescriptionCompat.Builder()
            .setMediaId(/*from   w  w w  .ja v  a 2 s.c  o m*/
                    MediaBrowserConstants.MEDIA_ID_PREFIX_ALBUM.concat(c.getString(AlbumsProviderKt.COLUMN_ID)))
            .setTitle(c.getString(AlbumsProviderKt.COLUMN_ALBUM));
    final String art = c.getString(AlbumsProviderKt.COLUMN_ALBUM_ART);
    if (!TextUtils.isEmpty(art)) {
        final Uri uri = FileProvider.getUriForFile(mContext,
                mContext.getPackageName().concat(".provider.album_thumbs"), new File(art));
        for (final String p : mMediaBrowserCallerPackageNames) {
            mContext.grantUriPermission(p, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        description.setIconUri(uri);
    }
    return new MediaItem(description.build(), MediaItem.FLAG_PLAYABLE);
}

From source file:com.demo.firebase.MainActivity.java

@AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
    Log.d(TAG, "launchCamera");

    // Check that we have permission to read images from external storage.
    String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    if (!EasyPermissions.hasPermissions(this, perm)) {
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage), RC_STORAGE_PERMS, perm);
        return;/*ww w .  java2  s .co m*/
    }

    // Choose file storage location, must be listed in res/xml/file_paths.xml
    File dir = new File(Environment.getExternalStorageDirectory() + "/photos");
    File file = new File(dir, UUID.randomUUID().toString() + ".jpg");
    try {
        // Create directory if it does not exist.
        if (!dir.exists()) {
            dir.mkdir();
        }
        boolean created = file.createNewFile();
        Log.d(TAG, "file.createNewFile:" + file.getAbsolutePath() + ":" + created);
    } catch (IOException e) {
        Log.e(TAG, "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
    }

    // Create content:// URI for file, required since Android N
    // See: https://developer.android.com/reference/android/support/v4/content/FileProvider.html
    mFileUri = FileProvider.getUriForFile(this, "com.google.firebase.quickstart.firebasestorage.fileprovider",
            file);

    // Create and launch the intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

    // Grant permission to camera (this is required on KitKat and below)
    List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(takePictureIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, mFileUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    // Start picture-taking intent
    startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}

From source file:com.android.mail.browse.AttachmentActionHandler.java

public void shareAttachments(ArrayList<Parcelable> uris) {
    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    intent.setType("image/*");
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    try {/*from w  ww . j  a  va2  s  .  c  om*/
        mContext.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // couldn't find activity for SEND_MULTIPLE intent
        LogUtils.e(LOG_TAG, "Couldn't find Activity for intent", e);
    }
}

From source file:de.spiritcroc.ownlog.ui.fragment.LogAttachmentsShowFragment.java

private void openFile(LogItem.Attachment attachment) {
    Uri uri = FileHelper.getAttachmentFileShare(getActivity(), attachment);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, attachment.type);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);//from  w w  w . jav  a2 s  .  com
}

From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java

/** Called when a session detail view asks to send session results somewhere. 
 * Generates a link to the session report Uri, and lets the remote program read from it. 
 * The {@link RhetologContentProvider} generates the result file on demand.
 * // ww  w  .j av a2s.  com
 * */

@Override
public void onSessionSend(Context context, Uri session) {

    // Send to the program selected by the chooser below.
    Intent sendSession = new Intent(Intent.ACTION_SEND);

    // Permit to read from Rhetolog URIs.
    sendSession.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    // Note type of send as report.
    sendSession.setType(RhetologContract.RHETOLOG_TYPE_SESSION_REPORT);

    sendSession.putExtra(Intent.EXTRA_SUBJECT, "Sending session " + session);

    // Send text as text.
    sendSession.putExtra(Intent.EXTRA_TEXT, reportForSession(session));

    // Send text as URI to be read.
    sendSession.putExtra(Intent.EXTRA_STREAM,
            Uri.parse(RhetologContract.SESSIONSREPORT + "/" + session.getLastPathSegment()));

    // Permit user to choose target of send.
    context.startActivity(Intent.createChooser(sendSession, "Send session results"));
}