Example usage for android.content Intent createChooser

List of usage examples for android.content Intent createChooser

Introduction

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

Prototype

public static Intent createChooser(Intent target, CharSequence title) 

Source Link

Document

Convenience function for creating a #ACTION_CHOOSER Intent.

Usage

From source file:com.mibr.android.intelligentreminder.INeedToo.java

public void TrialIsEndingWarningOrLicensingFailed(String verbiage, Boolean wereDealingWithLicensingHere) {
    final Boolean wdwlh = wereDealingWithLicensingHere;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(verbiage).setCancelable(false)
            .setNeutralButton(R.string.msg_cus, new DialogInterface.OnClickListener() {
                @Override/*  w  ww . j av  a2s . c  om*/
                public void onClick(DialogInterface dialog, int id) {
                    String[] mailto = { "diamondsoftware222@gmail.com", "" };
                    Intent sendIntent = new Intent(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
                    sendIntent.putExtra(Intent.EXTRA_SUBJECT, "".toString());
                    sendIntent.putExtra(Intent.EXTRA_TEXT, "".toString());
                    sendIntent.setType("text/plain");
                    startActivity(Intent.createChooser(sendIntent, "Send EMail..."));
                }
            }).setPositiveButton(R.string.msg_register, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    Intent i4 = new Intent(INeedToo.this, INeedToPay.class);
                    startActivity(i4);
                }
            }).setNegativeButton(R.string.msg_cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (wdwlh) {
                        INeedToo.this.finish();
                    }
                }
            });
    AlertDialog alert = builder.create();
    try {
        alert.show();
    } catch (Exception ee33) {
        int bkhere = 3;
        int bkhere2 = bkhere;
    }
}

From source file:com.dwdesign.tweetings.fragment.UserProfileFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    if (mUser == null || mService == null)
        return false;
    switch (item.getItemId()) {
    case MENU_TAKE_PHOTO: {
        takePhoto();//from  ww  w  .j  a v a 2s .  c  o  m
        break;
    }
    case MENU_ADD_IMAGE: {
        pickImage();
        break;
    }
    case MENU_BANNER_TAKE_PHOTO: {
        takeBannerPhoto();
        break;
    }
    case MENU_BANNER_ADD_IMAGE: {
        pickBannerImage();
        break;
    }
    case MENU_TRACKING: {
        UpdateTrackingTask task = new UpdateTrackingTask(!tracking);
        task.execute();
        break;
    }
    case MENU_BLOCK: {
        if (mService == null || mFriendship == null) {
            break;
        }
        if (mFriendship.isSourceBlockingTarget()) {
            mService.destroyBlock(mAccountId, mUser.getId());
        } else {
            mService.createBlock(mAccountId, mUser.getId());
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        mService.reportSpam(mAccountId, mUser.getId());
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = mUser.getScreenName();
        final Uri uri = Filters.Users.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE).edit();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.Users.TEXT, screen_name);
        resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null);
        resolver.insert(uri, values);
        editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit();
        Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_MENTION: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final String name = mUser.getName();
        final String screen_name = mUser.getScreenName();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putString(INTENT_KEY_TEXT, "@" + screen_name + " ");
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_SEND_DIRECT_MESSAGE: {
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme(SCHEME_TWEETINGS);
        builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
        builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(mAccountId));
        builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, String.valueOf(mUser.getId()));
        startActivity(new Intent(Intent.ACTION_VIEW, builder.build()));
        break;
    }
    case MENU_VIEW_ON_TWITTER: {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://twitter.com/" + mUser.getScreenName()));
        startActivity(browserIntent);
        break;
    }
    case MENU_WANT_RETWEETS: {
        updateFriendship();
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_USER);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_USER, new ParcelableUser(mUser, mAccountId));
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(INTENT_ACTION_SET_COLOR);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_COLOR: {
        clearUserColor(getActivity(), mUserId);
        updateUserColor();
        break;
    }
    }
    return true;
}

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"/* www.  j a  va2  s  .com*/
 * 
 * "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.nttec.everychan.ui.presentation.BoardFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    //?  ? -//from   w  w w. ja  v  a 2s.  co m
    switch (item.getItemId()) {
    case R.id.context_menu_thumb_load_thumb:
        bitmapCache.asyncGet(
                ChanModels.hashAttachmentModel((AttachmentModel) lastContextMenuAttachment.getTag()),
                ((AttachmentModel) lastContextMenuAttachment.getTag()).thumbnail,
                resources.getDimensionPixelSize(R.dimen.post_thumbnail_size), chan, null, imagesDownloadTask,
                (ImageView) lastContextMenuAttachment.findViewById(R.id.post_thumbnail_image),
                imagesDownloadExecutor, Async.UI_HANDLER, true, R.drawable.thumbnail_error);
        return true;
    case R.id.context_menu_thumb_download:
        downloadFile((AttachmentModel) lastContextMenuAttachment.getTag());
        return true;
    case R.id.context_menu_thumb_copy_url:
        String url = chan.fixRelativeUrl(((AttachmentModel) lastContextMenuAttachment.getTag()).path);
        Clipboard.copyText(activity, url);
        Toast.makeText(activity, resources.getString(R.string.notification_url_copied, url), Toast.LENGTH_LONG)
                .show();
        return true;
    case R.id.context_menu_thumb_attachment_info:
        String info = Attachments.getAttachmentInfoString(chan,
                ((AttachmentModel) lastContextMenuAttachment.getTag()), resources);
        Toast.makeText(activity, info, Toast.LENGTH_LONG).show();
        return true;
    case R.id.context_menu_thumb_reverse_search:
        ReverseImageSearch.openDialog(activity,
                chan.fixRelativeUrl(((AttachmentModel) lastContextMenuAttachment.getTag()).path));
        return true;
    }

    //?  ?  ?
    int position = lastContextMenuPosition;
    if (item.getMenuInfo() != null && item.getMenuInfo() instanceof AdapterView.AdapterContextMenuInfo) {
        position = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
    }
    if (nullAdapterIsSet || position == -1 || adapter.getCount() <= position)
        return false;
    switch (item.getItemId()) {
    case R.id.context_menu_open_in_new_tab:
        UrlPageModel modelNewTab = new UrlPageModel();
        modelNewTab.chanName = chan.getChanName();
        modelNewTab.type = UrlPageModel.TYPE_THREADPAGE;
        modelNewTab.boardName = tabModel.pageModel.boardName;
        modelNewTab.threadNumber = adapter.getItem(position).sourceModel.parentThread;
        String tabTitle = null;
        String subject = adapter.getItem(position).sourceModel.subject;
        if (subject != null && subject.length() != 0) {
            tabTitle = subject;
        } else {
            Spanned spannedComment = adapter.getItem(position).spannedComment;
            if (spannedComment != null) {
                tabTitle = spannedComment.toString().replace('\n', ' ');
                if (tabTitle.length() > MAX_TITLE_LENGHT)
                    tabTitle = tabTitle.substring(0, MAX_TITLE_LENGHT);
            }
        }
        if (tabTitle != null)
            tabTitle = resources.getString(R.string.tabs_title_threadpage_loaded, modelNewTab.boardName,
                    tabTitle);
        UrlHandler.open(modelNewTab, activity, false, tabTitle);
        return true;
    case R.id.context_menu_thread_preview:
        showThreadPreviewDialog(position);
        return true;
    case R.id.context_menu_reply_no_reading:
        UrlPageModel model = new UrlPageModel();
        model.chanName = chan.getChanName();
        model.type = UrlPageModel.TYPE_THREADPAGE;
        model.boardName = tabModel.pageModel.boardName;
        model.threadNumber = adapter.getItem(position).sourceModel.parentThread;
        openPostForm(ChanModels.hashUrlPageModel(model), presentationModel.source.boardModel,
                getSendPostModel(model));
        return true;
    case R.id.context_menu_hide:
        adapter.getItem(position).hidden = true;
        database.addHidden(tabModel.pageModel.chanName, tabModel.pageModel.boardName,
                pageType == TYPE_POSTSLIST ? tabModel.pageModel.threadNumber
                        : adapter.getItem(position).sourceModel.number,
                pageType == TYPE_POSTSLIST ? adapter.getItem(position).sourceModel.number : null);
        adapter.notifyDataSetChanged();
        return true;
    case R.id.context_menu_reply:
        openReply(position, false, null);
        return true;
    case R.id.context_menu_reply_with_quote:
        openReply(position, true, null);
        return true;
    case R.id.context_menu_select_text:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && lastContextMenuPosition == -1) {
            int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
            int wantedChild = position - firstPosition;
            if (wantedChild >= 0 && wantedChild < listView.getChildCount()) {
                View v = listView.getChildAt(wantedChild);
                if (v != null && v.getTag() != null && v.getTag() instanceof PostsListAdapter.PostViewTag) {
                    ((PostsListAdapter.PostViewTag) v.getTag()).commentView.startSelection();
                    return true;
                }
            }
        }
        Clipboard.copyText(activity, adapter.getItem(position).spannedComment.toString());
        Toast.makeText(activity, resources.getString(R.string.notification_comment_copied), Toast.LENGTH_LONG)
                .show();
        return true;
    case R.id.context_menu_share:
        UrlPageModel sharePostUrlPageModel = new UrlPageModel();
        sharePostUrlPageModel.chanName = chan.getChanName();
        sharePostUrlPageModel.type = UrlPageModel.TYPE_THREADPAGE;
        sharePostUrlPageModel.boardName = tabModel.pageModel.boardName;
        sharePostUrlPageModel.threadNumber = tabModel.pageModel.threadNumber;
        sharePostUrlPageModel.postNumber = adapter.getItem(position).sourceModel.number;

        Intent sharePostIntent = new Intent(Intent.ACTION_SEND);
        sharePostIntent.setType("text/plain");
        sharePostIntent.putExtra(Intent.EXTRA_SUBJECT, chan.buildUrl(sharePostUrlPageModel));
        sharePostIntent.putExtra(Intent.EXTRA_TEXT, adapter.getItem(position).spannedComment.toString());
        startActivity(Intent.createChooser(sharePostIntent, resources.getString(R.string.share_via)));
        return true;
    case R.id.context_menu_delete:
        DeletePostModel delModel = new DeletePostModel();
        delModel.chanName = chan.getChanName();
        delModel.boardName = tabModel.pageModel.boardName;
        delModel.threadNumber = tabModel.pageModel.threadNumber;
        delModel.postNumber = adapter.getItem(position).sourceModel.number;
        runDelete(delModel, adapter.getItem(position).sourceModel.attachments != null
                && adapter.getItem(position).sourceModel.attachments.length > 0);
        return true;
    case R.id.context_menu_report:
        DeletePostModel reportModel = new DeletePostModel();
        reportModel.chanName = chan.getChanName();
        reportModel.boardName = tabModel.pageModel.boardName;
        reportModel.threadNumber = tabModel.pageModel.threadNumber;
        reportModel.postNumber = adapter.getItem(position).sourceModel.number;
        runReport(reportModel);
        return true;
    case R.id.context_menu_subscribe:
        String chanName = chan.getChanName();
        String board = tabModel.pageModel.boardName;
        String thread = tabModel.pageModel.threadNumber;
        String post = adapter.getItem(position).sourceModel.number;
        if (subscriptions.hasSubscription(chanName, board, thread, post)) {
            subscriptions.removeSubscription(chanName, board, thread, post);
            for (int i = position; i < adapter.getCount(); ++i)
                adapter.getItem(i).onUnsubscribe(post);
        } else {
            subscriptions.addSubscription(chanName, board, thread, post);
            for (int i = position; i < adapter.getCount(); ++i)
                adapter.getItem(i).onSubscribe(post);
        }
        adapter.notifyDataSetChanged();
        return true;
    }
    return false;
}

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

private boolean archiveWalletBackup(@Nonnull final File file) {
    Uri shareableUri = null;/*w ww  .ja v a  2  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:RhodesService.java

/** Opens remote or local URL
 * @throws URISyntaxException, ActivityNotFoundException */
public static void openExternalUrl(String url) throws URISyntaxException, ActivityNotFoundException {
    //        try
    //        {//from   w  ww  . j  ava 2 s.c om
    if (url.charAt(0) == '/')
        url = "file://" + RhoFileApi.absolutePath(url);

    //FIXME: Use common URI handling
    Context ctx = RhodesService.getContext();
    LocalFileHandler fileHandler = new LocalFileHandler(ctx);
    if (!fileHandler.handle(url)) {
        Logger.D(TAG, "Handling URI: " + url);

        Intent intent = Intent.parseUri(url, 0);
        ctx.startActivity(Intent.createChooser(intent, "Open in..."));
    }
    //        }
    //        catch (Exception e) {
    //            Logger.E(TAG, "Can't open url :'" + url + "': " + e.getMessage());
    //        }
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

/**
 * Share all contacts that are currently selected. This method is pretty inefficient for
 * handling large numbers of contacts. I don't expect this to be a problem.
 *///w  w w  .j a v a 2 s.c  o  m
private void shareSelectedContacts() {
    final StringBuilder uriListBuilder = new StringBuilder();
    for (Long contactId : getSelectedContactIds()) {
        final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        final Uri lookupUri = ContactsContract.Contacts.getLookupUri(getContext().getContentResolver(),
                contactUri);
        if (lookupUri == null) {
            continue;
        }
        final List<String> pathSegments = lookupUri.getPathSegments();
        if (pathSegments.size() < 2) {
            continue;
        }
        final String lookupKey = pathSegments.get(pathSegments.size() - 2);
        if (uriListBuilder.length() > 0) {
            uriListBuilder.append(':');
        }
        uriListBuilder.append(Uri.encode(lookupKey));
    }
    if (uriListBuilder.length() == 0) {
        return;
    }
    final Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_MULTI_VCARD_URI,
            Uri.encode(uriListBuilder.toString()));
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(ContactsContract.Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    try {
        startActivityForResult(Intent.createChooser(intent, getResources()
                .getQuantityString(R.plurals.title_share_via, /* quantity */ getSelectedContactIds().size())),
                ACTIVITY_REQUEST_CODE_SHARE);
    } catch (final ActivityNotFoundException ex) {
        Toast.makeText(getContext(), R.string.share_error, Toast.LENGTH_SHORT).show();
    }
}

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

private void launchPhotoEditor() {
    /// M: [BUG.ADD] abort editing photo if loading fail @{
    if (mModel != null && mModel.getLoadingState(0) == PhotoView.Model.LOADING_FAIL) {
        Log.i(TAG, "<launchPhotoEditor> abort editing photo if loading fail!");
        Toast.makeText(mActivity, mActivity.getString(R.string.cannot_load_image), Toast.LENGTH_SHORT).show();
        return;/*ww w.j  a v a  2s  . co  m*/
    }
    /// @}
    MediaItem current = mModel.getMediaItem(0);
    if (current == null || (current.getSupportedOperations() & MediaObject.SUPPORT_EDIT) == 0) {
        return;
    }

    Intent intent = new Intent(ACTION_NEXTGEN_EDIT);

    /// M: [BUG.MODIFY] create new task when launch photo editor from camera
    // gallery and photo editor use same task stack @{
    /*
    intent.setDataAndType(current.getContentUri(), current.getMimeType())
          .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    */
    intent.setDataAndType(current.getContentUri(), current.getMimeType())
            .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
    /// @}
    if (mActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
            .size() == 0) {
        intent.setAction(Intent.ACTION_EDIT);
    }
    intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen());
    /// M: [FEATURE.ADD] @{
    // for special image, no need to delete origin image when save, such as continuous shot
    ExtItem extItem = current.getExtItem();
    if (extItem != null && !extItem.isDeleteOriginFileAfterEdit()) {
        // if current photo is last image in continuous shot group, not
        // set NEED_SAVE_AS as true
        if (mModel instanceof PhotoDataAdapter) {
            int size = ((PhotoDataAdapter) mModel).getTotalCount();
            MediaData md = current.getMediaData();
            if (size == 1 && md.mediaType == MediaData.MediaType.NORMAL
                    && md.subType == MediaData.SubType.CONSHOT) {
                intent.putExtra(FilterShowActivity.NEED_SAVE_AS, false);
                Log.i(TAG, "<launchPhotoEditor> edit the last image in continuous shot group,"
                        + " not set NEED_SAVE_AS as true");
            } else {
                intent.putExtra(FilterShowActivity.NEED_SAVE_AS, true);
            }
        } else {
            intent.putExtra(FilterShowActivity.NEED_SAVE_AS, true);
        }
    }
    /// @}

    /// M: [BUG.MODIFY] @{
    // Make ChooserActivity and GalleryActivity in different tasks.
    /*
     * ((Activity)mActivity).startActivityForResult(Intent.createChooser(intent
     * , null), REQUEST_EDIT);
     */
    ((Activity) mActivity).startActivityForResult(
            Intent.createChooser(intent, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), REQUEST_EDIT);
    /// @}

    overrideTransitionToEditor();
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

@Override
public void onAttachImage() {
    try {//from  w w w .j  a v  a2  s . com
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//prior Api level 19
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            Intent chooserIntent = Intent.createChooser(intent, null);
            startActivityForResult(chooserIntent, Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            Intent chooserIntent = Intent.createChooser(intent, null);
            startActivityForResult(chooserIntent, Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER);
        }
        imagePickerStillOpen = true;
    } catch (Exception e) {
        e.printStackTrace();
        imagePickerStillOpen = false;
        ApptentiveLog.d("can't launch image picker");
    }
}

From source file:com.asksven.betterbatterystats.StatsActivity.java

public Dialog getShareDialog() {

    final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>();

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean saveDumpfile = sharedPrefs.getBoolean("save_dumpfile", true);
    boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false);
    boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false);

    if (saveDumpfile) {
        selectedSaveActions.add(0);/*  ww  w.  jav a 2s .  com*/
    }
    if (saveLogcat) {
        selectedSaveActions.add(1);
    }
    if (saveDmesg) {
        selectedSaveActions.add(2);
    }

    //----
    LinearLayout layout = new LinearLayout(this);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(parms);

    layout.setGravity(Gravity.CLIP_VERTICAL);
    layout.setPadding(2, 2, 2, 2);

    final TextView editTitle = new TextView(StatsActivity.this);
    editTitle.setText(R.string.share_dialog_edit_title);
    editTitle.setPadding(40, 40, 40, 40);
    editTitle.setGravity(Gravity.LEFT);
    editTitle.setTextSize(20);

    final EditText editDescription = new EditText(StatsActivity.this);

    LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    tv1Params.bottomMargin = 5;
    layout.addView(editTitle, tv1Params);
    layout.addView(editDescription, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    //----

    // Set the dialog title
    builder.setTitle(R.string.title_share_dialog)
            .setMultiChoiceItems(R.array.saveAsLabels, new boolean[] { saveDumpfile, saveLogcat, saveDmesg },
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            if (isChecked) {
                                // If the user checked the item, add it to the
                                // selected items
                                selectedSaveActions.add(which);
                            } else if (selectedSaveActions.contains(which)) {
                                // Else, if the item is already in the array,
                                // remove it
                                selectedSaveActions.remove(Integer.valueOf(which));
                            }
                        }
                    })
            .setView(layout)
            // Set the action buttons
            .setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    ArrayList<Uri> attachements = new ArrayList<Uri>();

                    Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                            StatsActivity.this);
                    Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                            StatsActivity.this);

                    Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                    // save as text is selected
                    if (selectedSaveActions.contains(0)) {
                        attachements.add(reading.writeDumpfile(StatsActivity.this,
                                editDescription.getText().toString()));
                    }
                    // save logcat if selected
                    if (selectedSaveActions.contains(1)) {
                        attachements.add(StatsProvider.getInstance().writeLogcatToFile());
                    }
                    // save dmesg if selected
                    if (selectedSaveActions.contains(2)) {
                        attachements.add(StatsProvider.getInstance().writeDmesgToFile());
                    }

                    if (!attachements.isEmpty()) {
                        Intent shareIntent = new Intent();
                        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements);
                        shareIntent.setType("text/*");
                        startActivity(Intent.createChooser(shareIntent, "Share info to.."));
                    }
                }
            }).setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    try {
                        Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                                StatsActivity.this);
                        Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                                StatsActivity.this);

                        Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                        // save as text is selected
                        if (selectedSaveActions.contains(0)) {
                            reading.writeDumpfile(StatsActivity.this, editDescription.getText().toString());
                        }
                        // save logcat if selected
                        if (selectedSaveActions.contains(1)) {
                            StatsProvider.getInstance().writeLogcatToFile();
                        }
                        // save dmesg if selected
                        if (selectedSaveActions.contains(2)) {
                            StatsProvider.getInstance().writeDmesgToFile();
                        }

                        Snackbar.make(findViewById(android.R.id.content), getString(R.string.info_files_written)
                                + ": " + StatsProvider.getWritableFilePath(), Snackbar.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Log.e(TAG, "an error occured writing files: " + e.getMessage());
                        Snackbar.make(findViewById(android.R.id.content), R.string.info_files_write_error,
                                Snackbar.LENGTH_LONG).show();
                    }

                }
            }).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });

    return builder.create();
}