Contacts:  Contacts selection enhancements

1. Add "Select all" menu to allow user select all contacts.
2. Support to share multiple contacts asynchronously because share large
   contacts in main thread will leads to ANR.
3. Fix force close when more than 1000 selected contacts need to be deleted.
   Also add dialog to tell user contacts deletion progress.
4. Set max size as 9 when link multiple contacts.

Change-Id: I0f882274604397920f90938be7d0ae40ac025ca3
CRs-Fixed: 2401921
diff --git a/res/menu/people_options.xml b/res/menu/people_options.xml
index 5fb0f2e..18707e3 100644
--- a/res/menu/people_options.xml
+++ b/res/menu/people_options.xml
@@ -45,4 +45,9 @@
         android:title="@string/menu_joinAggregate"
         contacts:showAsAction="ifRoom"/>
 
+    <item
+        android:id="@+id/menu_select_all"
+        android:title="@string/menu_select_all"
+        contacts:showAsAction="never"/>
+
 </menu>
diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml
index f0fc421..2948e96 100644
--- a/res/values-zh-rCN/strings.xml
+++ b/res/values-zh-rCN/strings.xml
@@ -92,6 +92,7 @@
     <string name="multipleContactDeleteConfirmation" msgid="5235324124905653550">"删除此联系人也将删除多个帐号中的相关详细信息。"</string>
     <string name="deleteConfirmation" msgid="3512271779086656043">"要删除此联系人吗?"</string>
     <string name="deleteConfirmation_positive_button" msgid="7857888845028586365">"删除"</string>
+    <string name="delete_contacts_title">删除联系人</string>
     <string name="invalidContactMessage" msgid="8215051456181842274">"该联系人不存在。"</string>
     <string name="createContactShortcutSuccessful_NoName" msgid="8831303345367275472">"已将该联系人添加到主屏幕。"</string>
     <string name="createContactShortcutSuccessful" msgid="953651153238790069">"已将<xliff:g id="NAME">%s</xliff:g>添加到主屏幕。"</string>
@@ -135,6 +136,7 @@
     <string name="missing_app" msgid="1466111003546611387">"未找到可处理此操作的应用。"</string>
     <string name="menu_share" msgid="943789700636542260">"分享"</string>
     <string name="menu_add_contact" msgid="3198704337220892684">"添加到通讯录"</string>
+    <string name="menu_select_all">全选</string>
     <string name="menu_add_contacts" msgid="4465646512002163011">"添加"</string>
     <plurals name="title_share_via" formatted="false" msgid="5886112726191455415">
       <item quantity="other">通过以下应用分享联系人</item>
diff --git a/res/values/ids.xml b/res/values/ids.xml
index 82d14b2..751d667 100644
--- a/res/values/ids.xml
+++ b/res/values/ids.xml
@@ -25,6 +25,9 @@
     <!-- For ContactMultiDeletionInteraction -->
     <item type="id" name="dialog_delete_multiple_contact_loader_id" />
 
+    <!-- For ContactMultiShareInteraction -->
+    <item type="id" name="dialog_share_multiple_contact_loader_id" />
+
     <!-- For PhoneNumberInteraction -->
     <item type="id" name="dialog_phone_number_call_disambiguation"/>
 
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 8ebbced..96a5731 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -232,6 +232,9 @@
     <!-- Positive button text of confirmation dialog contents after users selects to delete a Writable contact. [CHAR LIMIT=30] -->
     <string name="deleteConfirmation_positive_button">Delete</string>
 
+    <!-- Deleting dialog, shown after users selects to delete multiple contacts writable contacts. [CHAR LIMIT=NONE]  -->
+    <string name="delete_contacts_title">Deleting contacts</string>
+
     <!-- Message displayed in a toast when you try to view the details of a contact that
          for some reason doesn't exist anymore. [CHAR LIMIT=NONE]-->
     <string name="invalidContactMessage">The contact doesn\'t exist.</string>
@@ -366,6 +369,9 @@
     <!-- The menu item to share the currently viewed contact [CHAR LIMIT=30] -->
     <string name="menu_share">Share</string>
 
+    <!-- The menu item to select all contacts -->
+    <string name="menu_select_all">Select all</string>
+
     <!-- The menu item to add the the currently viewed contact to your contacts [CHAR LIMIT=30] -->
     <string name="menu_add_contact">Add to contacts</string>
 
diff --git a/src/com/android/contacts/ContactSaveService.java b/src/com/android/contacts/ContactSaveService.java
index 0530ef7..4372488 100644
--- a/src/com/android/contacts/ContactSaveService.java
+++ b/src/com/android/contacts/ContactSaveService.java
@@ -166,6 +166,9 @@
     public static final int RESULT_UNKNOWN = 0;
     public static final int RESULT_SUCCESS = 1;
     public static final int RESULT_FAILURE = 2;
+    public static final int CONTACTS_DELETE_STARTED = 0;
+    public static final int CONTACTS_DELETE_INCREMENT = 1;
+    public static final int CONTACTS_DELETE_COMPLETE = 2;
 
     private static final HashSet<String> ALLOWED_DATA_COLUMNS = Sets.newHashSet(
         Data.MIMETYPE,
@@ -1183,10 +1186,19 @@
      */
     public static Intent createDeleteMultipleContactsIntent(Context context,
             long[] contactIds, final String[] names) {
+        return createDeleteMultipleContactsIntent(context, contactIds, names, /* receiver = */null);
+    }
+
+    /**
+     * Creates an intent that can be sent to this service to delete multiple contacts.
+     */
+    public static Intent createDeleteMultipleContactsIntent(Context context,
+            long[] contactIds, final String[] names, ResultReceiver receiver) {
         Intent serviceIntent = new Intent(context, ContactSaveService.class);
         serviceIntent.setAction(ContactSaveService.ACTION_DELETE_MULTIPLE_CONTACTS);
         serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_IDS, contactIds);
         serviceIntent.putExtra(ContactSaveService.EXTRA_DISPLAY_NAME_ARRAY, names);
+        serviceIntent.putExtra(ContactSaveService.EXTRA_RESULT_RECEIVER, receiver);
         return serviceIntent;
     }
 
@@ -1206,9 +1218,13 @@
             Log.e(TAG, "Invalid arguments for deleteMultipleContacts request");
             return;
         }
+        final ResultReceiver receiver = intent.getParcelableExtra(
+                ContactSaveService.EXTRA_RESULT_RECEIVER);
+        notifyActionProgress(CONTACTS_DELETE_STARTED, receiver);
         for (long contactId : contactIds) {
             final Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
             getContentResolver().delete(contactUri, null, null);
+            notifyActionProgress(CONTACTS_DELETE_INCREMENT, receiver);
         }
         final String[] names = intent.getStringArrayExtra(
                 ContactSaveService.EXTRA_DISPLAY_NAME_ARRAY);
@@ -1227,6 +1243,7 @@
                     R.string.contacts_deleted_many_named_toast, (Object[]) names);
         }
 
+        notifyActionProgress(CONTACTS_DELETE_COMPLETE, receiver);
         mMainHandler.post(new Runnable() {
             @Override
             public void run() {
@@ -1236,6 +1253,12 @@
         });
     }
 
+    private void notifyActionProgress(int state, ResultReceiver receiver){
+        if (receiver != null) {
+            receiver.send(state, new Bundle());
+        }
+    }
+
     /**
      * Creates an intent that can be sent to this service to split a contact into it's constituent
      * pieces. This will set the raw contact ids to {@link AggregationExceptions#TYPE_AUTOMATIC} so
diff --git a/src/com/android/contacts/interactions/ContactMultiDeletionInteraction.java b/src/com/android/contacts/interactions/ContactMultiDeletionInteraction.java
index 47b76a5..605e0fb 100644
--- a/src/com/android/contacts/interactions/ContactMultiDeletionInteraction.java
+++ b/src/com/android/contacts/interactions/ContactMultiDeletionInteraction.java
@@ -18,9 +18,12 @@
 
 import android.app.Activity;
 import android.app.AlertDialog;
+import android.app.ProgressDialog;
 import android.app.Fragment;
 import android.app.FragmentManager;
 import android.app.LoaderManager.LoaderCallbacks;
+import android.os.Handler;
+import android.support.v4.os.ResultReceiver;
 import android.content.Context;
 import android.content.CursorLoader;
 import android.content.DialogInterface;
@@ -82,6 +85,7 @@
     private TreeSet<Long> mContactIds;
     private Context mContext;
     private AlertDialog mDialog;
+    private ProgressDialog mProgressDialog;
     private MultiContactDeleteListener mListener;
 
     /**
@@ -165,19 +169,17 @@
     public Loader<Cursor> onCreateLoader(int id, Bundle args) {
         final TreeSet<Long> contactIds = (TreeSet<Long>) args.getSerializable(ARG_CONTACT_IDS);
         final Object[] parameterObject = contactIds.toArray();
-        final String[] parameters = new String[contactIds.size()];
 
-        final StringBuilder builder = new StringBuilder();
+        final StringBuilder builder = new StringBuilder(RawContacts.CONTACT_ID + " in (");
         for (int i = 0; i < contactIds.size(); i++) {
-            parameters[i] = String.valueOf(parameterObject[i]);
-            builder.append(RawContacts.CONTACT_ID + " =?");
-            if (i == contactIds.size() -1) {
-                break;
+            if (i > 0){
+                builder.append(",");
             }
-            builder.append(" OR ");
+            builder.append(String.valueOf(parameterObject[i]));
         }
+        builder.append(")");
         return new CursorLoader(mContext, RawContacts.CONTENT_URI, RAW_CONTACT_PROJECTION,
-                builder.toString(), parameters, null);
+                builder.toString(), null, null);
     }
 
     @Override
@@ -310,9 +312,44 @@
         }
     }
 
+    private void showProgressDialog(){
+        CharSequence title = getString(R.string.delete_contacts_title);
+
+        mProgressDialog = new ProgressDialog(mContext);
+        mProgressDialog.setTitle(title);
+        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
+        mProgressDialog.setProgress(0);
+        mProgressDialog.setMax(mContactIds.size());
+        mProgressDialog.setCancelable(false);
+        mProgressDialog.show();
+    }
+
     protected void doDeleteContact(long[] contactIds, final String[] names) {
+        ResultReceiver receiver = new ResultReceiver(new Handler()){
+            @Override
+            protected void onReceiveResult(int resultCode, Bundle resultData) {
+                super.onReceiveResult(resultCode, resultData);
+                switch (resultCode){
+                    case ContactSaveService.CONTACTS_DELETE_STARTED:
+                        showProgressDialog();
+                        break;
+                    case ContactSaveService.CONTACTS_DELETE_INCREMENT:
+                        if (mProgressDialog != null){
+                            mProgressDialog.incrementProgressBy(1);
+                        }
+                        break;
+                    case ContactSaveService.CONTACTS_DELETE_COMPLETE:
+                        if (mProgressDialog != null){
+                            mProgressDialog.dismiss();
+                            mProgressDialog = null;
+                        }
+                        break;
+                }
+            }
+        };
+
         mContext.startService(ContactSaveService.createDeleteMultipleContactsIntent(mContext,
-                contactIds, names));
+                contactIds, names, receiver));
         mListener.onDeletionFinished();
     }
 
diff --git a/src/com/android/contacts/interactions/ContactMultiShareInteraction.java b/src/com/android/contacts/interactions/ContactMultiShareInteraction.java
new file mode 100644
index 0000000..8d34b9e
--- /dev/null
+++ b/src/com/android/contacts/interactions/ContactMultiShareInteraction.java
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) 2019, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+     * Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+     * Redistributions in binary form must reproduce the above
+       copyright notice, this list of conditions and the following
+       disclaimer in the documentation and/or other materials provided
+       with the distribution.
+     * Neither the name of The Linux Foundation nor the names of its
+       contributors may be used to endorse or promote products derived
+       from this software without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.contacts.interactions;
+
+import android.content.Intent;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.ProgressDialog;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.app.LoaderManager.LoaderCallbacks;
+import android.provider.ContactsContract;
+import android.content.ActivityNotFoundException;
+import android.content.Context;
+import android.content.ContentUris;
+import android.content.AsyncTaskLoader;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnDismissListener;
+import android.content.DialogInterface.OnClickListener;
+import android.content.Loader;
+import android.net.Uri;
+import android.os.Bundle;
+import android.text.TextUtils;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.android.contacts.ContactSaveService;
+import com.android.contacts.R;
+
+import java.util.List;
+import java.util.TreeSet;
+/**
+ * An interaction invoked to share multiple contacts.
+ */
+public class ContactMultiShareInteraction extends Fragment
+        implements LoaderCallbacks<String> {
+
+    private static final int ACTIVITY_REQUEST_CODE_SHARE = 0;
+
+    private static final String FRAGMENT_TAG = "shareMultipleContacts";
+    private static final String TAG = "ContactMultiShare";
+    private static final String KEY_ACTIVE = "active";
+    private static final String KEY_CONTACTS_IDS = "contactIds";
+    public static final String ARG_CONTACT_IDS = "contactIds";
+
+    private boolean mIsLoaderActive;
+    private TreeSet<Long> mContactIds;
+    private Context mContext;
+    private static ProgressDialog mProgressDialog;
+
+    /**
+     * Starts the interaction.
+     *
+     * @param hostFragment the fragment within which to start the interaction
+     * @param contactIds the IDs of contacts to be shared
+     * @return the newly created interaction
+     */
+    public static ContactMultiShareInteraction start(
+            Fragment hostFragment, TreeSet<Long> contactIds) {
+        if (contactIds == null) {
+            return null;
+        }
+
+        final FragmentManager fragmentManager = hostFragment.getFragmentManager();
+        ContactMultiShareInteraction fragment =
+                (ContactMultiShareInteraction) fragmentManager.findFragmentByTag(FRAGMENT_TAG);
+        if (fragment == null) {
+            fragment = new ContactMultiShareInteraction();
+            fragment.setContactIds(contactIds);
+            fragmentManager.beginTransaction().add(fragment, FRAGMENT_TAG)
+                    .commitAllowingStateLoss();
+        } else {
+            fragment.setContactIds(contactIds);
+        }
+        return fragment;
+    }
+
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        mContext = activity;
+    }
+
+    @Override
+    public void onDestroyView() {
+        super.onDestroyView();
+        if (mProgressDialog != null && mProgressDialog.isShowing()) {
+            mProgressDialog.setOnDismissListener(null);
+            mProgressDialog.dismiss();
+            mProgressDialog = null;
+        }
+    }
+
+    public void setContactIds(TreeSet<Long> contactIds) {
+        mContactIds = contactIds;
+        mIsLoaderActive = true;
+        if (isStarted()) {
+            Bundle args = new Bundle();
+            args.putSerializable(ARG_CONTACT_IDS, mContactIds);
+            getLoaderManager().restartLoader(R.id.dialog_share_multiple_contact_loader_id,
+                    args, this);
+            showDialog();
+        }
+    }
+
+    private boolean isStarted() {
+        return isAdded();
+    }
+
+    @Override
+    public void onStart() {
+        if (mIsLoaderActive) {
+            Bundle args = new Bundle();
+            args.putSerializable(ARG_CONTACT_IDS, mContactIds);
+            getLoaderManager().initLoader(
+                    R.id.dialog_share_multiple_contact_loader_id, args, this);
+            showDialog();
+        }
+        super.onStart();
+    }
+
+    @Override
+    public void onStop() {
+        super.onStop();
+        if (mProgressDialog != null){
+            mProgressDialog.dismiss();
+        }
+    }
+
+    @Override
+    public Loader<String> onCreateLoader(int id, Bundle args) {
+        final TreeSet<Long> contactIds = (TreeSet<Long>) args.getSerializable(ARG_CONTACT_IDS);
+        return new ShareContactsLoader(mContext, contactIds);
+    }
+
+    @Override
+    public void onLoadFinished(Loader<String> loader, String uriList) {
+        if (mProgressDialog != null){
+            mProgressDialog.dismiss();
+            mProgressDialog = null;
+        }
+
+        if (!mIsLoaderActive) {
+            return;
+        }
+
+        if (TextUtils.isEmpty(uriList)) {
+            Log.e(TAG, "Failed to load contacts");
+            return;
+        }
+
+        final Uri uri = Uri.withAppendedPath(
+                ContactsContract.Contacts.CONTENT_MULTI_VCARD_URI,
+                Uri.encode(uriList));
+        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, mContext.getResources().getQuantityString(
+                    R.plurals.title_share_via,/* quantity */ mContactIds.size()))
+                    , ACTIVITY_REQUEST_CODE_SHARE);
+        } catch (final ActivityNotFoundException ex) {
+            Toast.makeText(getContext(), R.string.share_error, Toast.LENGTH_SHORT).show();
+        }
+
+        // We don't want onLoadFinished() calls any more, which may come when the database is
+        // updating.
+        getLoaderManager().destroyLoader(R.id.dialog_share_multiple_contact_loader_id);
+    }
+
+    @Override
+    public void onLoaderReset(Loader<String> loader) {
+    }
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putBoolean(KEY_ACTIVE, mIsLoaderActive);
+        outState.putSerializable(KEY_CONTACTS_IDS, mContactIds);
+    }
+
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+        if (savedInstanceState != null) {
+            mIsLoaderActive = savedInstanceState.getBoolean(KEY_ACTIVE);
+            mContactIds = (TreeSet<Long>) savedInstanceState.getSerializable(KEY_CONTACTS_IDS);
+        }
+    }
+
+    private void cancelLoad(){
+        Loader loader = getLoaderManager().getLoader(R.id.dialog_share_multiple_contact_loader_id);
+        if (loader != null){
+            loader.cancelLoad();
+        }
+    }
+
+    private void showDialog(){
+        CharSequence title = getString(R.string.exporting_contact_list_title);
+
+        mProgressDialog = new ProgressDialog(mContext);
+        mProgressDialog.setTitle(title);
+        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
+        mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
+                getString(android.R.string.cancel), (OnClickListener)null);
+        mProgressDialog.setProgress(0);
+        mProgressDialog.setMax(mContactIds.size());
+        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
+            @Override
+            public void onDismiss(DialogInterface dialog) {
+                cancelLoad();
+                mIsLoaderActive = false;
+                mProgressDialog = null;
+            }
+        });
+
+        mProgressDialog.show();
+    }
+
+    private static class ShareContactsLoader extends AsyncTaskLoader<String>{
+        private TreeSet<Long> mSelectedContactIds;
+
+        public ShareContactsLoader(Context context, TreeSet<Long> contactIds){
+            super(context);
+            mSelectedContactIds = contactIds;
+        }
+
+        @Override
+        protected void onStartLoading() {
+            forceLoad();
+        }
+
+        @Override
+        public String loadInBackground() {
+            final StringBuilder uriListBuilder = new StringBuilder();
+            for (Long contactId : mSelectedContactIds) {
+                if (!isLoadInBackgroundCanceled()) {
+                    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 (mProgressDialog != null) {
+                        mProgressDialog.incrementProgressBy(1);
+                    }
+                }
+
+            }
+            return uriListBuilder.toString();
+        }
+    }
+}
\ No newline at end of file
diff --git a/src/com/android/contacts/list/DefaultContactBrowseListFragment.java b/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
index 9851d2b..b4f748c 100644
--- a/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
+++ b/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
@@ -62,6 +62,7 @@
 import com.android.contacts.activities.ActionBarAdapter;
 import com.android.contacts.activities.PeopleActivity;
 import com.android.contacts.compat.CompatUtils;
+import com.android.contacts.interactions.ContactMultiShareInteraction;
 import com.android.contacts.interactions.ContactDeletionInteraction;
 import com.android.contacts.interactions.ContactMultiDeletionInteraction;
 import com.android.contacts.interactions.ContactMultiDeletionInteraction.MultiContactDeleteListener;
@@ -1015,8 +1016,10 @@
                 && getSelectedContactIds().size() != 0;
         makeMenuItemVisible(menu, R.id.menu_share, showSelectedContactOptions);
         makeMenuItemVisible(menu, R.id.menu_delete, showSelectedContactOptions);
+        makeMenuItemVisible(menu, R.id.menu_select_all, !isSearchOrSelectionMode);
         final boolean showLinkContactsOptions = mActionBarAdapter.isSelectionMode()
-                && getSelectedContactIds().size() > 1;
+                && getSelectedContactIds().size() > 1
+                && getSelectedContactIds().size() <= 9;
         makeMenuItemVisible(menu, R.id.menu_join, showLinkContactsOptions);
 
         // Debug options need to be visible even in search mode.
@@ -1085,6 +1088,10 @@
             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
             ImplicitIntentsUtil.startActivityOutsideApp(getContext(), intent);
             return true;
+        } else if (id == R.id.menu_select_all){
+            mActionBarAdapter.setSelectionMode(true);
+            mActivity.invalidateOptionsMenu();
+            setSelectedAll();
         }
         return super.onOptionsItemSelected(item);
     }
@@ -1094,41 +1101,9 @@
      * handling large numbers of contacts. I don't expect this to be a problem.
      */
     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();
-        }
+        final ContactMultiShareInteraction multiShareInteraction =
+                ContactMultiShareInteraction.start(this, getSelectedContactIds());
+        mActionBarAdapter.setSelectionMode(false);
     }
 
     private void joinSelectedContacts() {
diff --git a/src/com/android/contacts/list/MultiSelectContactsListFragment.java b/src/com/android/contacts/list/MultiSelectContactsListFragment.java
index 5e7f9e8..1d6b900 100644
--- a/src/com/android/contacts/list/MultiSelectContactsListFragment.java
+++ b/src/com/android/contacts/list/MultiSelectContactsListFragment.java
@@ -189,6 +189,23 @@
         }
     }
 
+    /**
+     * @param selected all contacts
+     */
+    public void setSelectedAll() {
+        TreeSet<Long> allContactIds = new TreeSet<Long>();
+        for (int i = 0; i < getAdapter().getCount(); i++) {
+            final long contactId = getContactId(i);
+            if (contactId < 0) {
+                return;
+            }
+            allContactIds.add(contactId);
+        }
+        if (getAdapter().isDisplayingCheckBoxes()) {
+            getAdapter().setSelectedContactIds(allContactIds);
+        }
+    }
+
     private long getContactId(int position) {
         final int contactIdColumnIndex = getAdapter().getContactColumnIdIndex();