Example usage for android.content Intent EXTRA_INITIAL_INTENTS

List of usage examples for android.content Intent EXTRA_INITIAL_INTENTS

Introduction

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

Prototype

String EXTRA_INITIAL_INTENTS

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

Click Source Link

Document

A Parcelable[] of Intent or android.content.pm.LabeledIntent objects as set with #putExtra(String,Parcelable[]) of additional activities to place a the front of the list of choices, when shown to the user with a #ACTION_CHOOSER .

Usage

From source file:com.aimfire.gallery.GalleryActivity.java

/**
 * share only to certain apps. code based on "http://stackoverflow.com/questions/
 * 9730243/how-to-filter-specific-apps-for-action-send-intent-and-set-a-different-
 * text-for/18980872#18980872"/*w w w .  j a  va 2 s.  c om*/
 * 
 * "copy link" inspired by http://cketti.de/2016/06/15/share-url-to-clipboard/
 * 
 * in general, "deep linking" is supported by the apps below. Facebook, Wechat,
 * Telegram are exceptions. click on the link would bring users to the landing
 * page. 
 * 
 * Facebook doesn't take our EXTRA_TEXT so user will have to "copy link" first 
 * then paste the link
 */
private void shareMedia(Intent data) {
    /*
     * we log this as "share complete", but user can still cancel the share at this point,
     * and we wouldn't be able to know
     */
    mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_SHARE_COMPLETE, null);

    Resources resources = getResources();

    /*
     * get the resource id for the shared file
     */
    String id = data.getStringExtra(MainConsts.EXTRA_ID_RESOURCE);

    /*
     * construct link
     */
    String link = "https://" + resources.getString(R.string.app_domain) + "/?id=" + id + "&name="
            + ((mPreviewName != null) ? mPreviewName : mMediaName);

    /*
     * message subject and text
     */
    String emailSubject, emailText, twitterText;

    if (MediaScanner.isPhoto(mMediaPath)) {
        emailSubject = resources.getString(R.string.emailSubjectPhoto);
        emailText = resources.getString(R.string.emailBodyPhotoPrefix) + link;
        twitterText = resources.getString(R.string.emailBodyPhotoPrefix) + link
                + resources.getString(R.string.twitterHashtagPhoto) + resources.getString(R.string.app_hashtag);
    } else if (MediaScanner.is3dMovie(mMediaPath)) {
        emailSubject = resources.getString(R.string.emailSubjectVideo);
        emailText = resources.getString(R.string.emailBodyVideoPrefix) + link;
        twitterText = resources.getString(R.string.emailBodyVideoPrefix) + link
                + resources.getString(R.string.twitterHashtagVideo) + resources.getString(R.string.app_hashtag);
    } else //if(MediaScanner.is2dMovie(mMediaPath))
    {
        emailSubject = resources.getString(R.string.emailSubjectVideo2d);
        emailText = resources.getString(R.string.emailBodyVideoPrefix2d) + link;
        twitterText = resources.getString(R.string.emailBodyVideoPrefix2d) + link
                + resources.getString(R.string.twitterHashtagVideo) + resources.getString(R.string.app_hashtag);
    }

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");

    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if (packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if (packageName.contains("twitter") || packageName.contains("facebook")
                || packageName.contains("whatsapp") || packageName.contains("tencent.mm") || //wechat
                packageName.contains("line") || packageName.contains("skype") || packageName.contains("viber")
                || packageName.contains("kik") || packageName.contains("sgiggle") || //tango
                packageName.contains("kakao") || packageName.contains("telegram")
                || packageName.contains("nimbuzz") || packageName.contains("hike")
                || packageName.contains("imoim") || packageName.contains("bbm")
                || packageName.contains("threema") || packageName.contains("mms")
                || packageName.contains("android.apps.messaging") || //google messenger
                packageName.contains("android.talk") || //google hangouts
                packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if (packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, twitterText);
            } else if (packageName.contains("facebook")) {
                /*
                 * the warning below is wrong! at least on GS5, Facebook client does take
                 * our text, however it seems it takes only the first hyperlink in the
                 * text.
                 * 
                 * Warning: Facebook IGNORES our text. They say "These fields are intended 
                 * for users to express themselves. Pre-filling these fields erodes the 
                 * authenticity of the user voice."
                 * One workaround is to use the Facebook SDK to post, but that doesn't 
                 * allow the user to choose how they want to share. We can also make a 
                 * custom landing page, and the link will show the <meta content ="..."> 
                 * text from that page with our link in Facebook.
                 */
                intent.putExtra(Intent.EXTRA_TEXT, link);
            } else if (packageName.contains("tencent.mm")) //wechat
            {
                /*
                 * wechat appears to do this similar to Facebook
                 */
                intent.putExtra(Intent.EXTRA_TEXT, link);
            } else if (packageName.contains("android.gm")) {
                // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
                //intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.setType("message/rfc822");
            } else if (packageName.contains("android.apps.docs")) {
                /*
                 * google drive - no reason to send link to it
                 */
                continue;
            } else {
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    /*
     *  create "Copy Link To Clipboard" Intent
     */
    Intent clipboardIntent = new Intent(this, CopyToClipboardActivity.class);
    clipboardIntent.setData(Uri.parse(link));
    intentList.add(new LabeledIntent(clipboardIntent, getPackageName(),
            getResources().getString(R.string.clipboard_activity_name), R.drawable.ic_copy_link));

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);
}

From source file:com.android.calendar.EventInfoFragment.java

/**
 * Generates an .ics formatted file with the event info and launches intent chooser to
 * share said file// www.jav  a 2 s. c  o  m
 */
public void shareEvent(ShareType type) {
    VCalendar calendar = generateVCalendar();
    // create and share ics file
    boolean isShareSuccessful = false;
    try {
        // event title serves as the file name prefix
        String filePrefix = calendar.getFirstEvent().getProperty(VEvent.SUMMARY);
        if (filePrefix == null || filePrefix.length() < 3) {
            // default to a generic filename if event title doesn't qualify
            // prefix length constraint is imposed by File#createTempFile
            filePrefix = "invite";
        }

        filePrefix = filePrefix.replaceAll("\\W+", " ");

        if (!filePrefix.endsWith(" ")) {
            filePrefix += " ";
        }

        File dir;
        if (type == ShareType.SDCARD) {
            dir = EXPORT_SDCARD_DIRECTORY;
            if (!dir.exists()) {
                dir.mkdir();
            }
        } else {
            dir = mActivity.getExternalCacheDir();
        }

        File inviteFile = IcalendarUtils.createTempFile(filePrefix, ".ics", dir);

        if (IcalendarUtils.writeCalendarToFile(calendar, inviteFile)) {
            if (type == ShareType.INTENT) {
                inviteFile.setReadable(true, false); // set world-readable
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(inviteFile));
                // the ics file is sent as an extra, the receiving application decides whether
                // to parse the file to extract calendar events or treat it as a regular file
                shareIntent.setType("application/octet-stream");

                Intent chooserIntent = Intent.createChooser(shareIntent,
                        getResources().getString(R.string.cal_share_intent_title));

                // The MMS app only responds to "text/x-vcalendar" so we create a chooser intent
                // that includes the targeted mms intent + any that respond to the above general
                // purpose "application/octet-stream" intent.
                File vcsInviteFile = File.createTempFile(filePrefix, ".vcs", mActivity.getExternalCacheDir());

                // for now , we are duplicating ics file and using that as the vcs file
                // TODO: revisit above
                if (IcalendarUtils.copyFile(inviteFile, vcsInviteFile)) {
                    Intent mmsShareIntent = new Intent();
                    mmsShareIntent.setAction(Intent.ACTION_SEND);
                    mmsShareIntent.setPackage("com.android.mms");
                    mmsShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcsInviteFile));
                    mmsShareIntent.setType("text/x-vcalendar");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { mmsShareIntent });
                }
                startActivity(chooserIntent);
            } else {
                if (!mInNonUiMode) {
                    String msg = getString(R.string.cal_export_succ_msg);
                    Toast.makeText(mActivity, String.format(msg, inviteFile), Toast.LENGTH_SHORT).show();
                }
            }
            isShareSuccessful = true;

        } else {
            // error writing event info to file
            isShareSuccessful = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        isShareSuccessful = false;
    }

    if (!isShareSuccessful) {
        Log.e(TAG, "Couldn't generate ics file");
        Toast.makeText(mActivity, R.string.error_generating_ics, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.dish.browser.activity.BrowserActivity.java

@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
    if (mFilePathCallback != null) {
        mFilePathCallback.onReceiveValue(null);
    }/*from  w w w . ja va  2 s.  c o  m*/
    mFilePathCallback = filePathCallback;

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = Utils.createImageFile();
            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.e(Constants.TAG, "Unable to create Image File", ex);
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        } else {
            takePictureIntent = null;
        }
    }

    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
    contentSelectionIntent.setType("image/*");

    Intent[] intentArray;
    if (takePictureIntent != null) {
        intentArray = new Intent[] { takePictureIntent };
    } else {
        intentArray = new Intent[0];
    }

    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
    chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

    mActivity.startActivityForResult(chooserIntent, 1);
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Allows to create a share intent and it can be launched.
 * //from  w ww.  j a v  a  2s  .  co m
 * @param context
 * @param type      Mime type.
 * @param nameApp   You can filter the application you want to share with. Use "wha", "twitt", etc.
 * @param title      The title of the share.Take in account that sometimes is not possible to add the title.
 * @param data      The data, can be a file or a text.
 * @param isBinaryData   If the share has a data file, set to TRUE otherwise FALSE.
 */
@SuppressLint("DefaultLocale")
public static Intent share_newSharingIntent(Context context, String type, String nameApp, String title,
        String data, boolean isBinaryData, boolean launch) {

    Intent res = null;

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType(type);

    List<Intent> targetedShareIntents = new ArrayList<Intent>();
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()) {
        for (ResolveInfo info : resInfo) {
            Intent targetedShare = new Intent(Intent.ACTION_SEND);
            targetedShare.setType(type);

            if (title != null) {
                targetedShare.putExtra(Intent.EXTRA_SUBJECT, title);
                targetedShare.putExtra(Intent.EXTRA_TITLE, title);
                if (data != null && !isBinaryData) {
                    targetedShare.putExtra(Intent.EXTRA_TEXT, data);
                }
            }
            if (data != null && isBinaryData) {
                targetedShare.putExtra(Intent.EXTRA_TEXT, title);
                targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(data)));
            }

            if (nameApp != null) {
                if (info.activityInfo.packageName.toLowerCase().contains(nameApp)
                        || info.activityInfo.name.toLowerCase().contains(nameApp)) {
                    targetedShare.setPackage(info.activityInfo.packageName);
                    targetedShareIntents.add(targetedShare);
                }
            } else {
                targetedShare.setPackage(info.activityInfo.packageName);
                targetedShareIntents.add(targetedShare);
            }
        }

        Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));

        res = chooserIntent;

        if (launch) {
            context.startActivity(chooserIntent);
        }
    }

    return res;
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

public void startMediaChooserDo() {

    Uri outputMediaUri = getCameraUri();
    Intent gallIntent = new Intent(Utils.getContentIntentAction());
    gallIntent.setType("image/*");
    Intent chooserIntent = Intent.createChooser(gallIntent, null);

    //if external storage is not available, camera capture won't work
    if (outputMediaUri != null) {
        Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputMediaUri);

        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { camIntent });
    }//w  ww. j av  a  2s. c  om
    Log.d(MyApplication.TAG, "starting chooser for PICTURE_REQUEST with EXTRA_OUTPUT = " + outputMediaUri);
    startActivityForResult(chooserIntent, ProtectedFragmentActivity.PICTURE_REQUEST_CODE);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
    case android.R.id.home:
        finishFragment();//from  w  w w. jav  a  2 s. com
        break;
    case R.id.attach_photo: {
        try {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File image = Utilities.generatePicturePath();
            if (image != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
                currentPicturePath = image.getAbsolutePath();
            }
            startActivityForResult(takePictureIntent, 0);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        break;
    }
    case R.id.attach_gallery: {
        try {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, 1);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        break;
    }
    case R.id.attach_video: {
        try {
            Intent pickIntent = new Intent();
            pickIntent.setType("video/*");
            pickIntent.setAction(Intent.ACTION_GET_CONTENT);
            pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000));
            Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            File video = Utilities.generateVideoPath();
            if (video != null) {
                if (android.os.Build.VERSION.SDK_INT > 16) {
                    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video));
                }
                takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000));
                currentPicturePath = video.getAbsolutePath();
            }
            Intent chooserIntent = Intent.createChooser(pickIntent, "");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takeVideoIntent });

            startActivityForResult(chooserIntent, 2);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        break;
    }
    case R.id.attach_location: {
        if (!isGoogleMapsInstalled()) {
            return true;
        }
        LocationActivity fragment = new LocationActivity();
        ((ApplicationActivity) parentActivity).presentFragment(fragment, "location", false);
        break;
    }
    case R.id.attach_document: {
        DocumentSelectActivity fragment = new DocumentSelectActivity();
        fragment.delegate = this;
        ((ApplicationActivity) parentActivity).presentFragment(fragment, "document", false);
        break;
    }
    }
    return true;
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private void showFileAttach() {
    final List<Intent> allIntents = new ArrayList<Intent>();

    // all openable...
    Intent contentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    contentIntent.setType(SafeSlingerConfig.MIMETYPE_ADD_ATTACH);
    contentIntent.addCategory(Intent.CATEGORY_OPENABLE);

    // camera//from  w ww. j ava2  s.  c om
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    SafeSlinger.setTempCameraFileUri(SSUtil.makeCameraOutputUri());
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, SafeSlinger.getTempCameraFileUri());
    allIntents.add(cameraIntent);

    // audio recorder
    Intent recorderIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    recorderIntent.putExtra(MediaStore.EXTRA_OUTPUT, SSUtil.makeRecorderOutputUri());
    allIntents.add(recorderIntent);

    // our custom browser
    if (SSUtil.isExternalStorageReadable()) {
        Intent filePickIntent = new Intent(HomeActivity.this, FilePickerActivity.class);
        LabeledIntent fileIntent = new LabeledIntent(filePickIntent, filePickIntent.getPackage(),
                R.string.menu_FileManager, R.drawable.ic_menu_directory);
        allIntents.add(fileIntent);
    }

    // Chooser of file system options.
    Intent chooserIntent = Intent.createChooser(contentIntent, getString(R.string.title_ChooseFileLoad));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[] {}));
    startActivityForResult(chooserIntent, VIEW_FILEATTACH_ID);
}

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  . j  av a 2s  . 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.zoffcc.applications.zanavi.Navit.java

void sendEmailWithAttachment(Context c, final String recipient, final String subject, final String message,
        final String full_file_name, final String full_file_name_suppl) {
    try {//from w w w  .j  a  va 2 s  . c o m
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", recipient, null));
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        ArrayList<Uri> uris = new ArrayList<>();
        uris.add(Uri.parse("file://" + full_file_name));
        try {
            if (new File(full_file_name_suppl).length() > 0) {
                uris.add(Uri.parse("file://" + full_file_name_suppl));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(emailIntent, 0);
        List<LabeledIntent> intents = new ArrayList<>();

        if (resolveInfos.size() != 0) {
            for (ResolveInfo info : resolveInfos) {
                Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                System.out.println(
                        "email:" + "comp=" + info.activityInfo.packageName + " " + info.activityInfo.name);
                intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
                intent.putExtra(Intent.EXTRA_EMAIL, new String[] { recipient });
                if (subject != null)
                    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
                if (message != null)
                    intent.putExtra(Intent.EXTRA_TEXT, message);
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                intents.add(new LabeledIntent(intent, info.activityInfo.packageName,
                        info.loadLabel(getPackageManager()), info.icon));
            }
            Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1),
                    Navit.get_text("Send email with attachments"));
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));
            startActivity(chooser);
        } else {
            System.out.println("email:" + "No Email App found");
            new AlertDialog.Builder(c).setMessage(Navit.get_text("No Email App found"))
                    .setPositiveButton(Navit.get_text("Ok"), null).show();
        }

        //         final Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", recipient, null));
        //         if (recipient != null) emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { recipient });
        //         if (subject != null) emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
        //         if (message != null) emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
        //         if (full_file_name != null)
        //         {
        //            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + full_file_name));
        //            //ArrayList<Uri> uris = new ArrayList<>();
        //            //uris.add(Uri.parse("file://" + full_file_name));
        //            //emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); //ArrayList<Uri> of attachment Uri's
        //         }
        //
        //         List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(emailIntent, 0);
        //         if (resolveInfos.size() != 0)
        //         {
        //            String packageName = resolveInfos.get(0).activityInfo.packageName;
        //            String name = resolveInfos.get(0).activityInfo.name;
        //
        //            emailIntent.setAction(Intent.ACTION_SEND);
        //            emailIntent.setComponent(new ComponentName(packageName, name));
        //
        //            System.out.println("email:" + "comp=" + packageName + " " + name);
        //
        //            startActivity(emailIntent);
        //         }
        //         else
        //         {
        //            System.out.println("email:" + "No Email App found");
        //            new AlertDialog.Builder(c).setMessage(Navit.get_text("No Email App found")).setPositiveButton(Navit.get_text("Ok"), null).show();
        //         }

    } catch (ActivityNotFoundException e) {
        // cannot send email for some reason
    }
}