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.afwsamples.testdpc.policy.PolicyManagementFragment.java

/**
 * Creates a content uri to be used with the capture intent.
 *//*from  w w  w. ja  va2s . c o  m*/
private Uri getStorageUri(String fileName) {
    final String filePath = getActivity().getFilesDir() + File.separator + "media" + File.separator + fileName;
    final File file = new File(filePath);
    // Create the folder if it doesn't exist.
    file.getParentFile().mkdirs();
    return FileProvider.getUriForFile(getActivity(), "com.afwsamples.testdpc.fileprovider", file);
}

From source file:org.telegram.ui.Components.AudioPlayerAlert.java

private void onSubItemClick(int id) {
    final MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
    if (messageObject == null || parentActivity == null) {
        return;/*from w ww  . ja v a2s. c  om*/
    }
    if (id == 1) {
        if (UserConfig.selectedAccount != currentAccount) {
            parentActivity.switchToAccount(currentAccount, true);
        }
        Bundle args = new Bundle();
        args.putBoolean("onlySelect", true);
        args.putInt("dialogsType", 3);
        DialogsActivity fragment = new DialogsActivity(args);
        final ArrayList<MessageObject> fmessages = new ArrayList<>();
        fmessages.add(messageObject);
        fragment.setDelegate((fragment1, dids, message, param) -> {
            if (dids.size() > 1 || dids.get(0) == UserConfig.getInstance(currentAccount).getClientUserId()
                    || message != null) {
                for (int a = 0; a < dids.size(); a++) {
                    long did = dids.get(a);
                    if (message != null) {
                        SendMessagesHelper.getInstance(currentAccount).sendMessage(message.toString(), did,
                                null, null, true, null, null, null);
                    }
                    SendMessagesHelper.getInstance(currentAccount).sendMessage(fmessages, did);
                }
                fragment1.finishFragment();
            } else {
                long did = dids.get(0);
                int lower_part = (int) did;
                int high_part = (int) (did >> 32);
                Bundle args1 = new Bundle();
                args1.putBoolean("scrollToTopOnResume", true);
                if (lower_part != 0) {
                    if (lower_part > 0) {
                        args1.putInt("user_id", lower_part);
                    } else if (lower_part < 0) {
                        args1.putInt("chat_id", -lower_part);
                    }
                } else {
                    args1.putInt("enc_id", high_part);
                }
                NotificationCenter.getInstance(currentAccount)
                        .postNotificationName(NotificationCenter.closeChats);
                ChatActivity chatActivity = new ChatActivity(args1);
                if (parentActivity.presentFragment(chatActivity, true, false)) {
                    chatActivity.showFieldPanelForForward(true, fmessages);
                } else {
                    fragment1.finishFragment();
                }
            }
        });
        parentActivity.presentFragment(fragment);
        dismiss();
    } else if (id == 2) {
        try {
            File f = null;
            boolean isVideo = false;

            if (!TextUtils.isEmpty(messageObject.messageOwner.attachPath)) {
                f = new File(messageObject.messageOwner.attachPath);
                if (!f.exists()) {
                    f = null;
                }
            }
            if (f == null) {
                f = FileLoader.getPathToMessage(messageObject.messageOwner);
            }

            if (f.exists()) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                if (messageObject != null) {
                    intent.setType(messageObject.getMimeType());
                } else {
                    intent.setType("audio/mp3");
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    try {
                        intent.putExtra(Intent.EXTRA_STREAM,
                                FileProvider.getUriForFile(ApplicationLoader.applicationContext,
                                        BuildConfig.APPLICATION_ID + ".provider", f));
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } catch (Exception ignore) {
                        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    }
                } else {
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                }

                parentActivity.startActivityForResult(Intent.createChooser(intent,
                        LocaleController.getString("ShareFile", R.string.ShareFile)), 500);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                builder.setMessage(LocaleController.getString("PleaseDownload", R.string.PleaseDownload));
                builder.show();
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    } else if (id == 3) {
        AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
        //builder.setMessage(LocaleController.formatString("AreYouSureDeleteAudio", R.string.AreYouSureDeleteAudio));
        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));

        final boolean deleteForAll[] = new boolean[1];
        int lower_id = (int) messageObject.getDialogId();
        if (lower_id != 0) {
            TLRPC.Chat currentChat;
            TLRPC.User currentUser;
            if (lower_id > 0) {
                currentUser = MessagesController.getInstance(currentAccount).getUser(lower_id);
                currentChat = null;
            } else {
                currentUser = null;
                currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id);
            }
            if (currentUser != null || !ChatObject.isChannel(currentChat)) {
                boolean hasOutgoing = false;
                int currentDate = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
                if (currentUser != null
                        && currentUser.id != UserConfig.getInstance(currentAccount).getClientUserId()
                        || currentChat != null) {
                    if ((messageObject.messageOwner.action == null
                            || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty)
                            && messageObject.isOut()
                            && (currentDate - messageObject.messageOwner.date) <= 2 * 24 * 60 * 60) {
                        FrameLayout frameLayout = new FrameLayout(parentActivity);
                        CheckBoxCell cell = new CheckBoxCell(parentActivity, 1);
                        cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                        if (currentChat != null) {
                            cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "",
                                    false, false);
                        } else {
                            cell.setText(LocaleController.formatString("DeleteForUser", R.string.DeleteForUser,
                                    UserObject.getFirstName(currentUser)), "", false, false);
                        }
                        cell.setPadding(
                                LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0,
                                LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
                        frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48,
                                Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
                        cell.setOnClickListener(v -> {
                            CheckBoxCell cell1 = (CheckBoxCell) v;
                            deleteForAll[0] = !deleteForAll[0];
                            cell1.setChecked(deleteForAll[0], true);
                        });
                        builder.setView(frameLayout);
                    }
                }
            }
        }
        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
            dismiss();
            ArrayList<Integer> arr = new ArrayList<>();
            arr.add(messageObject.getId());
            ArrayList<Long> random_ids = null;
            TLRPC.EncryptedChat encryptedChat = null;
            if ((int) messageObject.getDialogId() == 0 && messageObject.messageOwner.random_id != 0) {
                random_ids = new ArrayList<>();
                random_ids.add(messageObject.messageOwner.random_id);
                encryptedChat = MessagesController.getInstance(currentAccount)
                        .getEncryptedChat((int) (messageObject.getDialogId() >> 32));
            }
            MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat,
                    messageObject.messageOwner.to_id.channel_id, deleteForAll[0]);
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
        builder.show();
    } else if (id == 4) {
        if (UserConfig.selectedAccount != currentAccount) {
            parentActivity.switchToAccount(currentAccount, true);
        }

        Bundle args = new Bundle();
        long did = messageObject.getDialogId();
        int lower_part = (int) did;
        int high_id = (int) (did >> 32);
        if (lower_part != 0) {
            if (high_id == 1) {
                args.putInt("chat_id", lower_part);
            } else {
                if (lower_part > 0) {
                    args.putInt("user_id", lower_part);
                } else if (lower_part < 0) {
                    TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_part);
                    if (chat != null && chat.migrated_to != null) {
                        args.putInt("migrated_to", lower_part);
                        lower_part = -chat.migrated_to.channel_id;
                    }
                    args.putInt("chat_id", -lower_part);
                }
            }
        } else {
            args.putInt("enc_id", high_id);
        }
        args.putInt("message_id", messageObject.getId());
        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
        parentActivity.presentFragment(new ChatActivity(args), false, false);
        dismiss();
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private boolean archiveWalletBackup(@Nonnull final File file) {
    Uri shareableUri = null;//from w w w .jav a2 s.  c  o m
    try {
        shareableUri = FileProvider.getUriForFile(this, Constants.FILE_PROVIDER_AUTHORITY, file);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Backup file cannot be shared", e);
    }

    log.info("Shareable URI: {}", shareableUri);

    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_keys_dialog_mail_subject));
    intent.putExtra(Intent.EXTRA_TEXT,
            getString(R.string.export_keys_dialog_mail_text) + "\n\n"
                    + String.format(Constants.WEBMARKET_APP_URL, getPackageName()) + "\n\n"
                    + Constants.SOURCE_URL + '\n');
    intent.setType(Constants.MIMETYPE_WALLET_BACKUP);
    intent.putExtra(Intent.EXTRA_STREAM, shareableUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(Intent.createChooser(intent, getString(R.string.export_keys_dialog_mail_intent_chooser)));
        log.info("invoked chooser for archiving wallet backup");
        return true;
    } catch (final Exception x) {
        longToast(R.string.export_keys_dialog_mail_intent_failed);
        log.error("archiving wallet backup failed", x);
        return false;
    }
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private void initiateCameraApp() {
    addMediaBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);

    // We don't need to ask for permission in this case, because the used calls require
    // android.permission.WRITE_EXTERNAL_STORAGE only on SDKs *older* than Kitkat, which was
    // way before permission dialogues have been introduced.
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;/*  w w  w. j a v a  2  s  . c  o  m*/
        try {
            photoFile = createNewImageFile();
        } catch (IOException ex) {
            displayTransientError(R.string.error_media_upload_opening);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            photoUploadUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider",
                    photoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUploadUri);
            startActivityForResult(intent, MEDIA_TAKE_PHOTO_RESULT);
        }
    }
}

From source file:com.segma.trim.MainActivity.java

@Override
public void onProcessedResult(Bitmap bitmap) {
    switch (ACTION) {
    case ACTION_SHARE:
        try {/*from   w ww .  j a  va 2s . c  om*/
            File cacheDirectory = new File(getApplicationContext().getCacheDir().getPath() + "/images/");
            cacheDirectory.mkdirs();
            shareCacheUri = Uri
                    .parse(getApplicationContext().getCacheDir().getPath() + "/images/" + cacheFileName);
            // save to cache
            out = new FileOutputStream(shareCacheUri.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            File file = new File(shareCacheUri.getPath());
            shareCacheUri = FileProvider.getUriForFile(getApplicationContext(), "com.segma.trim.fileprovider",
                    file);

            // share CacheUri
            Intent send = ImageAPIParser.parse(this, getPackageManager(), shareCacheUri);
            if (send == null) {
                Toast.makeText(getApplicationContext(), WARNING_NO_APPROPRIATE_INTENT, Toast.LENGTH_LONG)
                        .show();
                break;
            }
            startActivityForResult(send, REQUEST_CODE_SHARE);

        } catch (Exception e) {
            Log.d(TAG, "Exception: " + e.toString());
            unlockMenu();
            unlockScreen();
            ipv.hideProgressDialog();
            e.printStackTrace();
        }
        ACTION = ACTION_SAVE;
        break;
    case ACTION_SAVE:
        //FIXME: UPDATE PENDING: custom saving location
        try {
            if (isOnRemovableSDCARDPath(PREF_SAVE_LOCATION_VALUE)) {
                MediaFile mediaFile = new MediaFile(getContentResolver(), new File(PREF_SAVE_LOCATION_VALUE
                        + "/result_" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".png"));
                out = mediaFile.write();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                Toast.makeText(getApplicationContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        unlockMenu();
                        unlockScreen();
                        ipv.hideProgressDialog();
                    }
                }, 2000);
                out.close();
                break;
            }

            out = new FileOutputStream(PREF_SAVE_LOCATION_VALUE + "/result_"
                    + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".png");
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            Toast.makeText(getApplicationContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    unlockMenu();
                    unlockScreen();
                    ipv.hideProgressDialog();
                }
            }, 2000);
            out.close();
        } catch (Exception e) {
            unlockMenu();
            unlockScreen();
            ipv.hideProgressDialog();
            Toast.makeText(getApplicationContext(), WARNING_SAVE_IMAGE_FAILED, Toast.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showSaveLocation();
                }
            }, 1000);
            e.printStackTrace();
        }
        break;
    }
}

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

private void sendLogs() {
    if (getParentActivity() == null) {
        return;/*from  w ww.  j  ava  2  s  . c o m*/
    }
    AlertDialog progressDialog = new AlertDialog(getParentActivity(), 3);
    progressDialog.setCanCacnel(false);
    progressDialog.show();
    Utilities.globalQueue.postRunnable(() -> {
        try {
            File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
            File dir = new File(sdCard.getAbsolutePath() + "/logs");

            File zipFile = new File(dir, "logs.zip");
            if (zipFile.exists()) {
                zipFile.delete();
            }

            File[] files = dir.listFiles();

            boolean[] finished = new boolean[1];

            BufferedInputStream origin = null;
            ZipOutputStream out = null;
            try {
                FileOutputStream dest = new FileOutputStream(zipFile);
                out = new ZipOutputStream(new BufferedOutputStream(dest));
                byte data[] = new byte[1024 * 64];

                for (int i = 0; i < files.length; i++) {
                    FileInputStream fi = new FileInputStream(files[i]);
                    origin = new BufferedInputStream(fi, data.length);

                    ZipEntry entry = new ZipEntry(files[i].getName());
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, data.length)) != -1) {
                        out.write(data, 0, count);
                    }
                    if (origin != null) {
                        origin.close();
                        origin = null;
                    }
                }
                finished[0] = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (origin != null) {
                    origin.close();
                }
                if (out != null) {
                    out.close();
                }
            }

            AndroidUtilities.runOnUIThread(() -> {
                try {
                    progressDialog.dismiss();
                } catch (Exception ignore) {

                }
                if (finished[0]) {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        uri = FileProvider.getUriForFile(getParentActivity(),
                                BuildConfig.APPLICATION_ID + ".provider", zipFile);
                    } else {
                        uri = Uri.fromFile(zipFile);
                    }

                    Intent i = new Intent(Intent.ACTION_SEND);
                    if (Build.VERSION.SDK_INT >= 24) {
                        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    i.setType("message/rfc822");
                    i.putExtra(Intent.EXTRA_EMAIL, "");
                    i.putExtra(Intent.EXTRA_SUBJECT, "Logs from "
                            + LocaleController.getInstance().formatterStats.format(System.currentTimeMillis()));
                    i.putExtra(Intent.EXTRA_STREAM, uri);
                    getParentActivity()
                            .startActivityForResult(Intent.createChooser(i, "Select email application."), 500);
                } else {
                    Toast.makeText(getParentActivity(),
                            LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred),
                            Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

From source file:net.bluehack.ui.MediaActivity.java

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;//  w  w w  .j av a  2  s .  c  om
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            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) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                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 {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    R.string.NoHandleAppInstalled, message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

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

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;/*from   ww w  . j  a  v a2s .  com*/
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            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) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                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 {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName",
                                    kr.wdream.storyshop.R.string.AppName));
                            builder.setPositiveButton(
                                    LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    kr.wdream.storyshop.R.string.NoHandleAppInstalled,
                                    message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * ??uri(?7.0)/*  w w w  . j av  a  2s. c  o  m*/
 * @param mContext
 * @param file
 * @return
 */
public static Uri getUriForFile(Context mContext, File file) {
    Uri fileUri = null;
    if (Build.VERSION.SDK_INT >= 24) {
        fileUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
    } else {
        fileUri = Uri.fromFile(file);
    }
    return fileUri;
}

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

public static void openForView(MessageObject message, Activity activity) throws Exception {
    File f = null;//from ww w  .  j  a v a  2s  . c  o m
    String fileName = message.getFileName();
    if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
        f = new File(message.messageOwner.attachPath);
    }
    if (f == null || !f.exists()) {
        f = FileLoader.getPathToMessage(message.messageOwner);
    }
    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 (message.type == 9 || message.type == 0) {
                    realMimeType = message.getDocument().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);
        }
    }
}