Example usage for android.support.v4.content FileProvider getUriForFile

List of usage examples for android.support.v4.content FileProvider getUriForFile

Introduction

In this page you can find the example usage for android.support.v4.content FileProvider getUriForFile.

Prototype

public static Uri getUriForFile(Context context, String str, File file) 

Source Link

Usage

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void openForView(TLObject media, Activity activity) throws Exception {
    if (media == null || activity == null) {
        return;/*from   w w w . ja va  2 s  . com*/
    }
    String fileName = FileLoader.getAttachFileName(media);
    File f = FileLoader.getPathToAttach(media, true);
    if (f != null && f.exists()) {
        String realMimeType = null;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        int idx = fileName.lastIndexOf('.');
        if (idx != -1) {
            String ext = fileName.substring(idx + 1);
            realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
            if (realMimeType == null) {
                if (media instanceof TLRPC.TL_document) {
                    realMimeType = ((TLRPC.TL_document) media).mime_type;
                }
                if (realMimeType == null || realMimeType.length() == 0) {
                    realMimeType = null;
                }
            }
        }
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(
                    FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                    realMimeType != null ? realMimeType : "text/plain");
        } else {
            intent.setDataAndType(Uri.fromFile(f), realMimeType != null ? realMimeType : "text/plain");
        }
        if (realMimeType != null) {
            try {
                activity.startActivityForResult(intent, 500);
            } catch (Exception e) {
                if (Build.VERSION.SDK_INT >= 24) {
                    intent.setDataAndType(
                            FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                            "text/plain");
                } else {
                    intent.setDataAndType(Uri.fromFile(f), "text/plain");
                }
                activity.startActivityForResult(intent, 500);
            }
        } else {
            activity.startActivityForResult(intent, 500);
        }
    }
}

From source file:com.owncloud.android.datamodel.FileDataStorageManager.java

public void triggerMediaScan(String path) {
    if (path != null) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        try {/*from w w w  . jav a 2s  .  c  o m*/
            intent.setData(FileProvider.getUriForFile(mContext.getApplicationContext(),
                    mContext.getResources().getString(R.string.file_provider_authority), new File(path)));
        } catch (IllegalArgumentException illegalArgumentException) {
            intent.setData(Uri.fromFile(new File(path)));
        }
        MainApp.getAppContext().sendBroadcast(intent);
    }
}

From source file:org.telegram.ui.ChannelAdminLogActivity.java

private void processSelectedOption(int option) {
    if (selectedObject == null) {
        return;//from w w w .j  a  va 2 s  . c  om
    }
    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.codename1.impl.android.AndroidImplementation.java

private Intent createIntentForURL(String url) {
    Intent intent;//from w  ww .  ja va 2s.co  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: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  ww.ja  v  a  2 s .c  o  m*/
        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:com.codename1.impl.android.AndroidImplementation.java

private String fixAttachmentPath(String attachment) {
    com.codename1.io.File cn1File = new com.codename1.io.File(attachment);
    File mediaStorageDir = new File(new File(getContext().getCacheDir(), "intent_files"), "Attachment");

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(Display.getInstance().getProperty("AppName", "CodenameOne"), "failed to create directory");
            return null;
        }/*from  w  w w. j  a va2s  .c  o  m*/
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File newFile = new File(
            mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + "_" + cn1File.getName());

    //Uri fileUri = Uri.fromFile(newFile);
    newFile.getParentFile().mkdirs();
    //Uri imageUri = Uri.fromFile(newFile);
    Uri fileUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
            newFile);

    try {
        InputStream is = FileSystemStorage.getInstance().openInputStream(attachment);
        OutputStream os = new FileOutputStream(newFile);
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > -1) {
            os.write(buf, 0, len);
        }
        is.close();
        os.close();
    } catch (IOException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
    }

    return fileUri.toString();
}

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

private void onActionClick(boolean download) {
    if (currentMessageObject == null && currentBotInlineResult == null || currentFileNames[0] == null) {
        return;//from   w w  w .  java2s .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");
    }/*  w  w w  .  j  av a  2s.  co  m*/
    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);
}

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

@Override
public void captureVideo(ActionListener response) {
    if (getActivity() == null) {
        throw new RuntimeException("Cannot capture video in background mode");
    }//w w w .j  av a 2 s .co m
    if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to take a video")) {
        return;
    }
    if (getRequestedPermissions().contains(Manifest.permission.CAMERA)) {
        // Normally we don't need to request the CAMERA permission since we use
        // the ACTION_VIDEO_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 video")) {
            return;
        }
    }
    callback = new EventDispatcher();
    callback.addListener(response);
    Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);

    File newFile = getOutputMediaFile(true);
    Uri videoUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
            newFile);

    Storage.getInstance().writeObject("videoUri", newFile.getAbsolutePath());

    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, videoUri);
    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, videoUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }

    this.getActivity().startActivityForResult(intent, CAPTURE_VIDEO);
}

From source file:org.telegram.ui.PassportActivity.java

private void processSelectedAttach(int which) {
    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;
        }//w  w w.  j  a v  a 2s .  c o  m
        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(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(0, false, false, null);
        fragment.setCurrentAccount(currentAccount);
        fragment.setMaxSelectedPhotos(getMaxSelectedDocuments());
        fragment.setAllowSearchImages(false);
        fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
            @Override
            public void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos) {
                processSelectedFiles(photos);
            }

            @Override
            public void startPhotoSelectActivity() {
                try {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    startActivityForResult(photoPickerIntent, 1);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        });
        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(false);
        fragment.setCurrentAccount(currentAccount);
        fragment.setCanSelectOnlyImageFiles(true);
        fragment.setMaxSelectedFiles(getMaxSelectedDocuments());
        fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() {
            @Override
            public void didSelectFiles(DocumentSelectActivity activity, ArrayList<String> files) {
                activity.finishFragment();
                ArrayList<SendMessagesHelper.SendingMediaInfo> arrayList = new ArrayList<>();
                for (int a = 0, count = files.size(); a < count; a++) {
                    SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                    info.path = files.get(a);
                    arrayList.add(info);
                }
                processSelectedFiles(arrayList);
            }

            @Override
            public void startDocumentSelectActivity() {
                try {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    if (Build.VERSION.SDK_INT >= 18) {
                        photoPickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    }
                    photoPickerIntent.setType("*/*");
                    startActivityForResult(photoPickerIntent, 21);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        });
        presentFragment(fragment);
    }
}