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:org.telegram.ui.ChannelAdminLogActivity.java

private void processSelectedOption(int option) {
    if (selectedObject == null) {
        return;/*from w  w w . ja v a2  s  . co  m*/
    }
    switch (option) {
    case 3: {
        AndroidUtilities.addToClipboard(getMessageContent(selectedObject, 0, true));
        break;
    }
    case 4: {
        String path = selectedObject.messageOwner.attachPath;
        if (path != null && path.length() > 0) {
            File temp = new File(path);
            if (!temp.exists()) {
                path = null;
            }
        }
        if (path == null || path.length() == 0) {
            path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString();
        }
        if (selectedObject.type == 3 || selectedObject.type == 1) {
            if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                getParentActivity()
                        .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                selectedObject = null;
                return;
            }
            MediaController.saveFile(path, getParentActivity(), selectedObject.type == 3 ? 1 : 0, null, null);
        }
        break;
    }
    case 5: {
        File locFile = null;
        if (selectedObject.messageOwner.attachPath != null
                && selectedObject.messageOwner.attachPath.length() != 0) {
            File f = new File(selectedObject.messageOwner.attachPath);
            if (f.exists()) {
                locFile = f;
            }
        }
        if (locFile == null) {
            File f = FileLoader.getPathToMessage(selectedObject.messageOwner);
            if (f.exists()) {
                locFile = f;
            }
        }
        if (locFile != null) {
            if (locFile.getName().toLowerCase().endsWith("attheme")) {
                if (chatLayoutManager != null) {
                    int lastPosition = chatLayoutManager.findLastVisibleItemPosition();
                    if (lastPosition < chatLayoutManager.getItemCount() - 1) {
                        scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition();
                        RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView
                                .findViewHolderForAdapterPosition(scrollToPositionOnRecreate);
                        if (holder != null) {
                            scrollToOffsetOnRecreate = holder.itemView.getTop();
                        } else {
                            scrollToPositionOnRecreate = -1;
                        }
                    } else {
                        scrollToPositionOnRecreate = -1;
                    }
                }
                Theme.ThemeInfo themeInfo = Theme.applyThemeFile(locFile, selectedObject.getDocumentName(),
                        true);
                if (themeInfo != null) {
                    presentFragment(new ThemePreviewActivity(locFile, themeInfo));
                } else {
                    scrollToPositionOnRecreate = -1;
                    if (getParentActivity() == null) {
                        selectedObject = null;
                        return;
                    }
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("IncorrectTheme", R.string.IncorrectTheme));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    showDialog(builder.create());
                }
            } else {
                if (LocaleController.getInstance().applyLanguageFile(locFile, currentAccount)) {
                    presentFragment(new LanguageSelectActivity());
                } else {
                    if (getParentActivity() == null) {
                        selectedObject = null;
                        return;
                    }
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("IncorrectLocalization",
                            R.string.IncorrectLocalization));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    showDialog(builder.create());
                }
            }
        }
        break;
    }
    case 6: {
        String path = selectedObject.messageOwner.attachPath;
        if (path != null && path.length() > 0) {
            File temp = new File(path);
            if (!temp.exists()) {
                path = null;
            }
        }
        if (path == null || path.length() == 0) {
            path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString();
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType(selectedObject.getDocument().mime_type);
        if (Build.VERSION.SDK_INT >= 24) {
            try {
                intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getParentActivity(),
                        BuildConfig.APPLICATION_ID + ".provider", new File(path)));
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } catch (Exception ignore) {
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
            }
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
        }
        getParentActivity().startActivityForResult(
                Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)), 500);
        break;
    }
    case 7: {
        String path = selectedObject.messageOwner.attachPath;
        if (path != null && path.length() > 0) {
            File temp = new File(path);
            if (!temp.exists()) {
                path = null;
            }
        }
        if (path == null || path.length() == 0) {
            path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString();
        }
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    4);
            selectedObject = null;
            return;
        }
        MediaController.saveFile(path, getParentActivity(), 0, null, null);
        break;
    }
    case 9: {
        showDialog(
                new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, null));
        break;
    }
    case 10: {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    4);
            selectedObject = null;
            return;
        }
        String fileName = FileLoader.getDocumentFileName(selectedObject.getDocument());
        if (TextUtils.isEmpty(fileName)) {
            fileName = selectedObject.getFileName();
        }
        String path = selectedObject.messageOwner.attachPath;
        if (path != null && path.length() > 0) {
            File temp = new File(path);
            if (!temp.exists()) {
                path = null;
            }
        }
        if (path == null || path.length() == 0) {
            path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString();
        }
        MediaController.saveFile(path, getParentActivity(), selectedObject.isMusic() ? 3 : 2, fileName,
                selectedObject.getDocument() != null ? selectedObject.getDocument().mime_type : "");
        break;
    }
    case 11: {
        TLRPC.Document document = selectedObject.getDocument();
        MessagesController.getInstance(currentAccount).saveGif(selectedObject, document);
        break;
    }
    case 15: {
        Bundle args = new Bundle();
        args.putInt("user_id", selectedObject.messageOwner.media.user_id);
        args.putString("phone", selectedObject.messageOwner.media.phone_number);
        args.putBoolean("addContact", true);
        presentFragment(new ContactAddActivity(args));
        break;
    }
    case 16: {
        AndroidUtilities.addToClipboard(selectedObject.messageOwner.media.phone_number);
        break;
    }
    case 17: {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL,
                    Uri.parse("tel:" + selectedObject.messageOwner.media.phone_number));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getParentActivity().startActivityForResult(intent, 500);
        } catch (Exception e) {
            FileLog.e(e);
        }
        break;
    }
    }
    selectedObject = null;
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (requestCode == RC_SIGN_IN && !mGoogleApiKey && mGoogleApiClient != null) {
        new Thread(new Runnable() {
            @Override//w  w  w  .j a  v a 2 s. c  om
            public void run() {
                mIntentInProgress = false;
                mGoogleApiKey = true;
                // !mGoogleApiClient.isConnecting
                if (mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                } else
                    mGoogleApiClient.disconnect();

            }
        }).run();
    } else if (requestCode == image_selector_request_code) {
        if (sharedPref != null && intent != null && intent.getData() != null) {
            if (SDK_INT >= 19)
                getContentResolver().takePersistableUriPermission(intent.getData(),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
            sharedPref.edit().putString("drawer_header_path", intent.getData().toString()).commit();
            setDrawerHeaderBackground();
        }
    } else if (requestCode == 3) {
        Uri treeUri;
        if (responseCode == Activity.RESULT_OK) {
            // Get Uri from Storage Access Framework.
            treeUri = intent.getData();
            // Persist URI - this is required for verification of writability.
            if (treeUri != null)
                sharedPref.edit().putString("URI", treeUri.toString()).commit();
        } else {
            // If not confirmed SAF, or if still not writable, then revert settings.
            /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false, currentFolder);
                ||!FileUtil.isWritableNormalOrSaf(currentFolder)*/
            return;
        }

        // After confirmation, update stored value of folder.
        // Persist access permissions.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        switch (operation) {
        case DataUtils.DELETE://deletion
            new DeleteTask(null, mainActivity).execute((oparrayList));
            break;
        case DataUtils.COPY://copying
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }
            for (int i = 0; i < oparrayListList.size(); i++) {
                Intent intent1 = new Intent(con, CopyService.class);
                intent1.putExtra(CopyService.TAG_COPY_SOURCES, oparrayList.get(i));
                intent1.putExtra(CopyService.TAG_COPY_TARGET, oppatheList.get(i));
                ServiceWatcherUtil.runService(this, intent1);
            }
            break;
        case DataUtils.MOVE://moving
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }

            new MoveFiles(oparrayListList, ((MainFragment) getFragment().getTab()),
                    getFragment().getTab().getActivity(), OpenMode.FILE)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, oppatheList);
            break;
        case DataUtils.NEW_FOLDER://mkdir
            MainFragment ma1 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkDir(RootHelper.generateBaseFile(new File(oppathe), true), ma1);
            break;
        case DataUtils.RENAME:
            MainFragment ma2 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.rename(ma2.openMode, (oppathe), (oppathe1), mainActivity, BaseActivity.rootMode);
            ma2.updateList();
            break;
        case DataUtils.NEW_FILE:
            MainFragment ma3 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkFile(new HFile(OpenMode.FILE, oppathe), ma3);

            break;
        case DataUtils.EXTRACT:
            mainActivityHelper.extractFile(new File(oppathe));
            break;
        case DataUtils.COMPRESS:
            mainActivityHelper.compressFiles(new File(oppathe), oparrayList);
        }
        operation = -1;
    } else if (requestCode == REQUEST_CODE_SAF && responseCode == Activity.RESULT_OK) {
        // otg access
        sharedPref.edit().putString(KEY_PREF_OTG, intent.getData().toString()).apply();

        if (!isDrawerLocked)
            mDrawerLayout.closeDrawer(mDrawerLinear);
        else
            onDrawerClosed();
    } else if (requestCode == REQUEST_CODE_SAF && responseCode != Activity.RESULT_OK) {
        // otg access not provided
        pendingPath = null;
    }
}

From source file:com.android.gallery3d.app.PhotoPage.java

private static Intent createShareIntent(Uri contentUri, int type) {
    return new Intent(Intent.ACTION_SEND).setType(MenuExecutor.getMimeType(type))
            .putExtra(Intent.EXTRA_STREAM, contentUri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private Intent createIntentForURL(String url) {
    Intent intent;/*www. java 2  s. c o  m*/
    Uri uri;
    try {
        if (url.startsWith("intent")) {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } else {
            if (url.startsWith("/") || url.startsWith("file:")) {
                if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        "This is required to open the file")) {
                    return null;
                }
            }
            intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            if (url.startsWith("/")) {
                File f = new File(url);
                Uri furi = null;
                try {
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
                            f);
                } catch (Exception ex) {
                    f = makeTempCacheCopy(f);
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
                            f);
                }

                if (Build.VERSION.SDK_INT < 21) {
                    List<ResolveInfo> resInfoList = getContext().getPackageManager()
                            .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        getContext().grantUriPermission(packageName, furi,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }

                uri = furi;
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {

                if (url.startsWith("file:")) {
                    File f = new File(removeFilePrefix(url));
                    System.out.println("File size: " + f.length());

                    Uri furi = null;
                    try {
                        furi = FileProvider.getUriForFile(getContext(),
                                getContext().getPackageName() + ".provider", f);
                    } catch (Exception ex) {
                        f = makeTempCacheCopy(f);
                        furi = FileProvider.getUriForFile(getContext(),
                                getContext().getPackageName() + ".provider", f);
                    }

                    if (Build.VERSION.SDK_INT < 21) {
                        List<ResolveInfo> resInfoList = getContext().getPackageManager()
                                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                        for (ResolveInfo resolveInfo : resInfoList) {
                            String packageName = resolveInfo.activityInfo.packageName;
                            getContext().grantUriPermission(packageName, furi,
                                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                            | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        }
                    }
                    uri = furi;
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);

                } else {
                    uri = Uri.parse(url);
                }
            }
            String mimeType = getMimeType(url);
            if (mimeType != null) {
                intent.setDataAndType(uri, mimeType);
            } else {
                intent.setData(uri);
            }
        }

        return intent;
    } catch (Exception err) {
        com.codename1.io.Log.e(err);
        return null;
    }
}

From source file:com.android.mail.compose.ComposeActivity.java

protected void sendOrSave(final boolean save, final boolean showToast) {
    // Check if user is a monkey. Monkeys can compose and hit send
    // button but are not allowed to send anything off the device.
    if (ActivityManager.isUserAMonkey()) {
        return;//w ww.  j a  v a 2 s  .c  o m
    }

    final SendOrSaveCallback callback = new SendOrSaveCallback() {
        @Override
        public void initializeSendOrSave() {
            final Intent i = new Intent(ComposeActivity.this, EmptyService.class);

            // API 16+ allows for setClipData. For pre-16 we are going to open the fds
            // on the main thread.
            if (Utils.isRunningJellybeanOrLater()) {
                // Grant the READ permission for the attachments to the service so that
                // as long as the service stays alive we won't hit PermissionExceptions.
                final ClipDescription desc = new ClipDescription("attachment_uris",
                        new String[] { ClipDescription.MIMETYPE_TEXT_URILIST });
                ClipData clipData = null;
                for (Attachment a : mAttachmentsView.getAttachments()) {
                    if (a != null && !Utils.isEmpty(a.contentUri)) {
                        final ClipData.Item uriItem = new ClipData.Item(a.contentUri);
                        if (clipData == null) {
                            clipData = new ClipData(desc, uriItem);
                        } else {
                            clipData.addItem(uriItem);
                        }
                    }
                }
                i.setClipData(clipData);
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

            synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
                if (PENDING_SEND_OR_SAVE_TASKS_NUM.getAndAdd(1) == 0) {
                    // Start service so we won't be killed if this app is
                    // put in the background.
                    startService(i);
                }
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.initializeSendOrSave();
            }
        }

        @Override
        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message) {
            synchronized (mDraftLock) {
                mDraftId = message.id;
                mDraft = message;
                if (sRequestMessageIdMap != null) {
                    sRequestMessageIdMap.put(sendOrSaveMessage.mRequestId, mDraftId);
                }
                // Cache request message map, in case the process is killed
                saveRequestMap();
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
            }
        }

        @Override
        public long getMessageId() {
            synchronized (mDraftLock) {
                return mDraftId;
            }
        }

        @Override
        public void sendOrSaveFinished(SendOrSaveMessage message, boolean success) {
            // Update the last sent from account.
            if (mAccount != null) {
                MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
            }
            if (success) {
                // Successfully sent or saved so reset change markers
                discardChanges();
            } else {
                // A failure happened with saving/sending the draft
                // TODO(pwestbro): add a better string that should be used
                // when failing to send or save
                Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT).show();
            }

            synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
                if (PENDING_SEND_OR_SAVE_TASKS_NUM.addAndGet(-1) == 0) {
                    // Stop service so we can be killed.
                    stopService(new Intent(ComposeActivity.this, EmptyService.class));
                }
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.sendOrSaveFinished(message, success);
            }
        }
    };
    setAccount(mReplyFromAccount.account);

    final Spanned body = removeComposingSpans(mBodyView.getText());
    callback.initializeSendOrSave();

    // For pre-JB we need to open the fds on the main thread
    final Bundle attachmentFds;
    if (!Utils.isRunningJellybeanOrLater()) {
        attachmentFds = initializeAttachmentFds(this, mAttachmentsView.getAttachments());
    } else {
        attachmentFds = null;
    }

    // Generate a unique message id for this request
    mRequestId = sRandom.nextInt();
    SEND_SAVE_TASK_HANDLER.post(new Runnable() {
        @Override
        public void run() {
            final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
            sendOrSaveInternal(ComposeActivity.this, mRequestId, mReplyFromAccount, mDraftAccount, msg,
                    mRefMessage, mQuotedTextView.getQuotedTextIfIncluded(), callback, save, mComposeMode,
                    mExtraValues, attachmentFds);
        }
    });

    // Don't display the toast if the user is just changing the orientation,
    // but we still need to save the draft to the cursor because this is how we restore
    // the attachments when the configuration change completes.
    if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
        Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message, Toast.LENGTH_LONG)
                .show();
    }

    // Need to update variables here because the send or save completes
    // asynchronously even though the toast shows right away.
    discardChanges();
    updateSaveUi();

    // If we are sending, finish the activity
    if (!save) {
        finish();
    }
}

From source file:kr.wdream.ui.ChatActivity.java

private void processSelectedAttach(int which) {
    if (which == attach_photo || which == attach_gallery || which == attach_document || which == attach_video) {
        String action;//from   w w w .j av  a 2 s .  c om
        if (currentChat != null) {
            if (currentChat.participants_count > MessagesController.getInstance().groupBigSize) {
                if (which == attach_photo || which == attach_gallery) {
                    action = "bigchat_upload_photo";
                } else {
                    action = "bigchat_upload_document";
                }
            } else {
                if (which == attach_photo || which == attach_gallery) {
                    action = "chat_upload_photo";
                } else {
                    action = "chat_upload_document";
                }
            }
        } else {
            if (which == attach_photo || which == attach_gallery) {
                action = "pm_upload_photo";
            } else {
                action = "pm_upload_document";
            }
        }
        if (!MessagesController.isFeatureEnabled(action, ChatActivity.this)) {
            return;
        }
    }

    if (which == attach_photo) {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity()
                .checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA }, 19);
            return;
        }
        try {
            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(
                            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();
            }
            startActivityForResult(takePictureIntent, 0);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    } else if (which == attach_gallery) {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                    4);
            return;
        }
        PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(false,
                currentEncryptedChat == null
                        || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46,
                true, ChatActivity.this);
        fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
            @Override
            public void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions,
                    ArrayList<ArrayList<TLRPC.InputDocument>> masks,
                    ArrayList<MediaController.SearchImage> webPhotos) {
                SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject,
                        captions, masks);
                SendMessagesHelper.prepareSendingPhotosSearch(webPhotos, dialog_id, replyingMessageObject);
                showReplyPanel(false, null, null, null, false, true);
                DraftQuery.cleanDraft(dialog_id, true);
            }

            @Override
            public void startPhotoSelectActivity() {
                try {
                    Intent videoPickerIntent = new Intent();
                    videoPickerIntent.setType("video/*");
                    videoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
                    videoPickerIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536));

                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    Intent chooserIntent = Intent.createChooser(photoPickerIntent, null);
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { videoPickerIntent });

                    startActivityForResult(chooserIntent, 1);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }

            @Override
            public boolean didSelectVideo(String path) {
                if (Build.VERSION.SDK_INT >= 16) {
                    return !openVideoEditor(path, true, true);
                } else {
                    SendMessagesHelper.prepareSendingVideo(path, 0, 0, 0, 0, null, dialog_id,
                            replyingMessageObject, null);
                    showReplyPanel(false, null, null, null, false, true);
                    DraftQuery.cleanDraft(dialog_id, true);
                    return true;
                }
            }
        });
        presentFragment(fragment);
    } else if (which == attach_video) {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity()
                .checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA }, 20);
            return;
        }
        try {
            Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            File video = AndroidUtilities.generateVideoPath();
            if (video != null) {
                if (Build.VERSION.SDK_INT >= 24) {
                    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(
                            getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", video));
                    takeVideoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else if (Build.VERSION.SDK_INT >= 18) {
                    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video));
                }
                takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536));
                currentPicturePath = video.getAbsolutePath();
            }
            startActivityForResult(takeVideoIntent, 2);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    } else if (which == attach_location) {
        if (!AndroidUtilities.isGoogleMapsInstalled(ChatActivity.this)) {
            return;
        }
        LocationActivity fragment = new LocationActivity();
        fragment.setDelegate(new LocationActivity.LocationActivityDelegate() {
            @Override
            public void didSelectLocation(TLRPC.MessageMedia location) {
                SendMessagesHelper.getInstance().sendMessage(location, dialog_id, replyingMessageObject, null,
                        null);
                moveScrollToLastMessage();
                showReplyPanel(false, null, null, null, false, true);
                DraftQuery.cleanDraft(dialog_id, true);
                if (paused) {
                    scrollToTopOnResume = true;
                }
            }
        });
        presentFragment(fragment);
    } else if (which == attach_document) {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                    4);
            return;
        }
        DocumentSelectActivity fragment = new DocumentSelectActivity();
        fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() {
            @Override
            public void didSelectFiles(DocumentSelectActivity activity, ArrayList<String> files) {
                activity.finishFragment();
                SendMessagesHelper.prepareSendingDocuments(files, files, null, null, dialog_id,
                        replyingMessageObject);
                showReplyPanel(false, null, null, null, false, true);
                DraftQuery.cleanDraft(dialog_id, true);
            }

            @Override
            public void startDocumentSelectActivity() {
                try {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("*/*");
                    startActivityForResult(photoPickerIntent, 21);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        });
        presentFragment(fragment);
    } else if (which == attach_audio) {
        if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            getParentActivity().requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                    4);
            return;
        }
        AudioSelectActivity fragment = new AudioSelectActivity();
        fragment.setDelegate(new AudioSelectActivity.AudioSelectActivityDelegate() {
            @Override
            public void didSelectAudio(ArrayList<MessageObject> audios) {
                SendMessagesHelper.prepareSendingAudioDocuments(audios, dialog_id, replyingMessageObject);
                showReplyPanel(false, null, null, null, false, true);
                DraftQuery.cleanDraft(dialog_id, true);
            }
        });
        presentFragment(fragment);
    } else if (which == attach_contact) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (getParentActivity().checkSelfPermission(
                    Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                getParentActivity().requestPermissions(new String[] { Manifest.permission.READ_CONTACTS }, 5);
                return;
            }
        }
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(intent, 31);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static void startStatusShareChooser(final Context context, final ParcelableStatus status) {
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    final String name = status.user_name, screenName = status.user_screen_name;
    final String timeString = formatToLongTimeString(context, status.timestamp);
    final String subject = context.getString(R.string.share_subject_format, name, screenName, timeString);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, status.text_plain);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
}

From source file:org.getlantern.firetweet.util.Utils.java

public static void startStatusShareChooser(final Context context, final ParcelableStatus status) {
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    final String name = status.user_name, screenName = status.user_screen_name;
    final String timeString = formatToLongTimeString(context, status.timestamp);
    final String subject = context.getString(R.string.status_share_subject_format_with_time, name, screenName,
            timeString);/*from   www.  j  a va 2  s. c o m*/
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, status.text_plain);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
}

From source file:kr.wdream.ui.PhotoViewer.java

private void onActionClick(boolean download) {
    if (currentMessageObject == null && currentBotInlineResult == null || currentFileNames[0] == null) {
        return;/*w  w w. j  ava 2s. c  om*/
    }
    File file = null;
    if (currentMessageObject != null) {
        if (currentMessageObject.messageOwner.attachPath != null
                && currentMessageObject.messageOwner.attachPath.length() != 0) {
            file = new File(currentMessageObject.messageOwner.attachPath);
            if (!file.exists()) {
                file = null;
            }
        }
        if (file == null) {
            file = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
            if (!file.exists()) {
                file = null;
            }
        }
    } else if (currentBotInlineResult != null) {
        if (currentBotInlineResult.document != null) {
            file = FileLoader.getPathToAttach(currentBotInlineResult.document);
            if (!file.exists()) {
                file = null;
            }
        } else {
            file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE),
                    Utilities.MD5(currentBotInlineResult.content_url) + "."
                            + ImageLoader.getHttpUrlExtension(currentBotInlineResult.content_url, "mp4"));
            if (!file.exists()) {
                file = null;
            }
        }
    }
    if (file == null) {
        if (download) {
            if (currentMessageObject != null) {
                if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) {
                    FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, false);
                } else {
                    FileLoader.getInstance().cancelLoadFile(currentMessageObject.getDocument());
                }
            } else if (currentBotInlineResult != null) {
                if (currentBotInlineResult.document != null) {
                    if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) {
                        FileLoader.getInstance().loadFile(currentBotInlineResult.document, true, false);
                    } else {
                        FileLoader.getInstance().cancelLoadFile(currentBotInlineResult.document);
                    }
                } else {
                    if (!ImageLoader.getInstance().isLoadingHttpFile(currentBotInlineResult.content_url)) {
                        ImageLoader.getInstance().loadHttpFile(currentBotInlineResult.content_url, "mp4");
                    } else {
                        ImageLoader.getInstance().cancelLoadHttpFile(currentBotInlineResult.content_url);
                    }
                }
            }
        }
    } else {
        if (Build.VERSION.SDK_INT >= 16) {
            preparePlayer(file, true);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(FileProvider.getUriForFile(parentActivity,
                        BuildConfig.APPLICATION_ID + ".provider", file), "video/mp4");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "video/mp4");
            }
            parentActivity.startActivityForResult(intent, 500);
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public void capturePhoto(ActionListener response) {
    if (getActivity() == null) {
        throw new RuntimeException("Cannot capture photo in background mode");
    }//from   ww  w  . j  a  va  2 s  .  com
    if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to take a picture")) {
        return;
    }
    if (getRequestedPermissions().contains(Manifest.permission.CAMERA)) {
        // Normally we don't need to request the CAMERA permission since we use
        // the ACTION_IMAGE_CAPTURE intent, which handles permissions itself.
        // BUT: If the camera permission is included in the Manifest file, the 
        // intent will defer to the app's permissions, and on Android 6, 
        // the permission is denied unless we do the runtime check for permission.
        // See https://github.com/codenameone/CodenameOne/issues/2409#issuecomment-391696058
        if (!checkForPermission(Manifest.permission.CAMERA, "This is required to take a picture")) {
            return;
        }
    }
    callback = new EventDispatcher();
    callback.addListener(response);
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    File newFile = getOutputMediaFile(false);
    newFile.getParentFile().mkdirs();
    newFile.getParentFile().setWritable(true, false);
    //Uri imageUri = Uri.fromFile(newFile);
    Uri imageUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
            newFile);
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);

    String lastImageID = getLastImageId();
    Storage.getInstance().writeObject("imageUri", newFile.getAbsolutePath() + ";" + lastImageID);

    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    if (Build.VERSION.SDK_INT < 21) {
        List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            getContext().grantUriPermission(packageName, imageUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }

    getActivity().startActivityForResult(intent, CAPTURE_IMAGE);
}