QuickContactActivity.java revision 35ccdba7b8b2270204f7f96d824d258e408fe6ef
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.contacts.quickcontact;
18
19import android.animation.Animator;
20import android.animation.Animator.AnimatorListener;
21import android.animation.AnimatorListenerAdapter;
22import android.animation.ArgbEvaluator;
23import android.animation.ObjectAnimator;
24import android.app.Activity;
25import android.app.Fragment;
26import android.app.LoaderManager.LoaderCallbacks;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Intent;
32import android.content.Loader;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.graphics.Bitmap;
36import android.graphics.Color;
37import android.graphics.PorterDuff;
38import android.graphics.PorterDuffColorFilter;
39import android.graphics.drawable.BitmapDrawable;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.net.ParseException;
43import android.net.Uri;
44import android.net.WebAddress;
45import android.os.AsyncTask;
46import android.os.Bundle;
47import android.os.Trace;
48import android.provider.CalendarContract;
49import android.provider.ContactsContract;
50import android.provider.ContactsContract.CommonDataKinds.Email;
51import android.provider.ContactsContract.CommonDataKinds.Event;
52import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
53import android.provider.ContactsContract.CommonDataKinds.Identity;
54import android.provider.ContactsContract.CommonDataKinds.Im;
55import android.provider.ContactsContract.CommonDataKinds.Nickname;
56import android.provider.ContactsContract.CommonDataKinds.Note;
57import android.provider.ContactsContract.CommonDataKinds.Organization;
58import android.provider.ContactsContract.CommonDataKinds.Phone;
59import android.provider.ContactsContract.CommonDataKinds.Relation;
60import android.provider.ContactsContract.CommonDataKinds.SipAddress;
61import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
62import android.provider.ContactsContract.CommonDataKinds.Website;
63import android.provider.ContactsContract.Contacts;
64import android.provider.ContactsContract.Data;
65import android.provider.ContactsContract.DisplayNameSources;
66import android.provider.ContactsContract.DataUsageFeedback;
67import android.provider.ContactsContract.QuickContact;
68import android.provider.ContactsContract.RawContacts;
69import android.support.v7.graphics.Palette;
70import android.text.TextUtils;
71import android.util.Log;
72import android.util.Pair;
73import android.view.Menu;
74import android.view.MenuInflater;
75import android.view.MenuItem;
76import android.view.View;
77import android.view.View.OnClickListener;
78import android.view.WindowManager;
79import android.widget.ImageView;
80import android.widget.Toast;
81import android.widget.Toolbar;
82
83import com.android.contacts.ContactSaveService;
84import com.android.contacts.ContactsActivity;
85import com.android.contacts.NfcHandler;
86import com.android.contacts.R;
87import com.android.contacts.common.CallUtil;
88import com.android.contacts.common.Collapser;
89import com.android.contacts.common.ContactsUtils;
90import com.android.contacts.common.editor.SelectAccountDialogFragment;
91import com.android.contacts.common.lettertiles.LetterTileDrawable;
92import com.android.contacts.common.list.ShortcutIntentBuilder;
93import com.android.contacts.common.list.ShortcutIntentBuilder.OnShortcutIntentCreatedListener;
94import com.android.contacts.common.model.AccountTypeManager;
95import com.android.contacts.common.model.Contact;
96import com.android.contacts.common.model.ContactLoader;
97import com.android.contacts.common.model.RawContact;
98import com.android.contacts.common.model.account.AccountType;
99import com.android.contacts.common.model.account.AccountWithDataSet;
100import com.android.contacts.common.model.dataitem.DataItem;
101import com.android.contacts.common.model.dataitem.DataKind;
102import com.android.contacts.common.model.dataitem.EmailDataItem;
103import com.android.contacts.common.model.dataitem.EventDataItem;
104import com.android.contacts.common.model.dataitem.ImDataItem;
105import com.android.contacts.common.model.dataitem.NicknameDataItem;
106import com.android.contacts.common.model.dataitem.NoteDataItem;
107import com.android.contacts.common.model.dataitem.OrganizationDataItem;
108import com.android.contacts.common.model.dataitem.PhoneDataItem;
109import com.android.contacts.common.model.dataitem.RelationDataItem;
110import com.android.contacts.common.model.dataitem.SipAddressDataItem;
111import com.android.contacts.common.model.dataitem.StructuredNameDataItem;
112import com.android.contacts.common.model.dataitem.StructuredPostalDataItem;
113import com.android.contacts.common.model.dataitem.WebsiteDataItem;
114import com.android.contacts.common.util.DateUtils;
115import com.android.contacts.common.util.MaterialColorMapUtils;
116import com.android.contacts.common.util.MaterialColorMapUtils.MaterialPalette;
117import com.android.contacts.detail.ContactDetailDisplayUtils;
118import com.android.contacts.interactions.CalendarInteractionsLoader;
119import com.android.contacts.interactions.CallLogInteractionsLoader;
120import com.android.contacts.interactions.ContactDeletionInteraction;
121import com.android.contacts.interactions.ContactInteraction;
122import com.android.contacts.interactions.SmsInteractionsLoader;
123import com.android.contacts.quickcontact.ExpandingEntryCardView.Entry;
124import com.android.contacts.quickcontact.ExpandingEntryCardView.ExpandingEntryCardViewListener;
125import com.android.contacts.util.ImageViewDrawableSetter;
126import com.android.contacts.util.PhoneCapabilityTester;
127import com.android.contacts.util.SchedulingUtils;
128import com.android.contacts.util.StructuredPostalUtils;
129import com.android.contacts.widget.MultiShrinkScroller;
130import com.android.contacts.widget.MultiShrinkScroller.MultiShrinkScrollerListener;
131import com.google.common.base.Preconditions;
132import com.google.common.collect.Lists;
133
134import java.util.ArrayList;
135import java.util.Arrays;
136import java.util.Calendar;
137import java.util.Collections;
138import java.util.Comparator;
139import java.util.Date;
140import java.util.HashMap;
141import java.util.List;
142import java.util.Map;
143
144/**
145 * Mostly translucent {@link Activity} that shows QuickContact dialog. It loads
146 * data asynchronously, and then shows a popup with details centered around
147 * {@link Intent#getSourceBounds()}.
148 */
149public class QuickContactActivity extends ContactsActivity {
150
151    /**
152     * QuickContacts immediately takes up the full screen. All possible information is shown.
153     * This value for {@link android.provider.ContactsContract.QuickContact#EXTRA_MODE}
154     * should only be used by the Contacts app.
155     */
156    public static final int MODE_FULLY_EXPANDED = 4;
157
158    private static final String TAG = "QuickContact";
159
160    private static final String KEY_THEME_COLOR = "theme_color";
161
162    private static final int ANIMATION_STATUS_BAR_COLOR_CHANGE_DURATION = 150;
163    private static final int REQUEST_CODE_CONTACT_EDITOR_ACTIVITY = 1;
164    private static final int SCRIM_COLOR = Color.argb(0xB2, 0, 0, 0);
165    private static final String MIMETYPE_SMS = "vnd.android-dir/mms-sms";
166
167    /** This is the Intent action to install a shortcut in the launcher. */
168    private static final String ACTION_INSTALL_SHORTCUT =
169            "com.android.launcher.action.INSTALL_SHORTCUT";
170
171    @SuppressWarnings("deprecation")
172    private static final String LEGACY_AUTHORITY = android.provider.Contacts.AUTHORITY;
173
174    private static final String MIMETYPE_GPLUS_PROFILE =
175            "vnd.android.cursor.item/vnd.googleplus.profile";
176    private static final String INTENT_DATA_GPLUS_PROFILE_ADD_TO_CIRCLE = "Add to circle";
177    private static final String MIMETYPE_HANGOUTS =
178            "vnd.android.cursor.item/vnd.googleplus.profile.comm";
179    private static final String INTENT_DATA_HANGOUTS_VIDEO = "Start video call";
180
181    private Uri mLookupUri;
182    private String[] mExcludeMimes;
183    private int mExtraMode;
184    private int mStatusBarColor;
185    private boolean mHasAlreadyBeenOpened;
186
187    private ImageView mPhotoView;
188    private View mTransparentView;
189    private ExpandingEntryCardView mContactCard;
190    private ExpandingEntryCardView mNoContactDetailsCard;
191    private ExpandingEntryCardView mRecentCard;
192    private ExpandingEntryCardView mAboutCard;
193    /**
194     * This list contains all the {@link DataItem}s. Each nested list contains all data items of a
195     * specific mimetype in sorted order, using mWithinMimeTypeDataItemComparator. The mimetype
196     * lists are sorted using mAmongstMimeTypeDataItemComparator.
197     */
198    private List<List<DataItem>> mDataItemsList;
199    /**
200     * A map between a mimetype string and the corresponding list of data items. The data items
201     * are in sorted order using mWithinMimeTypeDataItemComparator.
202     */
203    private Map<String, List<DataItem>> mDataItemsMap;
204    private MultiShrinkScroller mScroller;
205    private SelectAccountDialogFragmentListener mSelectAccountFragmentListener;
206    private AsyncTask<Void, Void, Pair<List<List<DataItem>>, Map<String, List<DataItem>>>>
207            mEntriesAndActionsTask;
208    private ColorDrawable mWindowScrim;
209    private MaterialColorMapUtils mMaterialColorMapUtils;
210    private boolean mIsWaitingForOtherPieceOfExitAnimation;
211    private boolean mIsExitAnimationInProgress;
212    private boolean mHasComputedThemeColor;
213
214    private Contact mContactData;
215    private ContactLoader mContactLoader;
216    private PorterDuffColorFilter mColorFilter;
217
218    private final ImageViewDrawableSetter mPhotoSetter = new ImageViewDrawableSetter();
219
220    /**
221     * {@link #LEADING_MIMETYPES} is used to sort MIME-types.
222     *
223     * <p>The MIME-types in {@link #LEADING_MIMETYPES} appear in the front of the dialog,
224     * in the order specified here.</p>
225     */
226    private static final List<String> LEADING_MIMETYPES = Lists.newArrayList(
227            Phone.CONTENT_ITEM_TYPE, SipAddress.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE,
228            StructuredPostal.CONTENT_ITEM_TYPE);
229
230    private static final List<String> ABOUT_CARD_MIMETYPES = Lists.newArrayList(
231            Event.CONTENT_ITEM_TYPE, GroupMembership.CONTENT_ITEM_TYPE, Identity.CONTENT_ITEM_TYPE,
232            Im.CONTENT_ITEM_TYPE, Nickname.CONTENT_ITEM_TYPE, Note.CONTENT_ITEM_TYPE,
233            Organization.CONTENT_ITEM_TYPE, Relation.CONTENT_ITEM_TYPE, Website.CONTENT_ITEM_TYPE);
234
235    /** Id for the background contact loader */
236    private static final int LOADER_CONTACT_ID = 0;
237
238    private static final String KEY_LOADER_EXTRA_PHONES =
239            QuickContactActivity.class.getCanonicalName() + ".KEY_LOADER_EXTRA_PHONES";
240
241    /** Id for the background Sms Loader */
242    private static final int LOADER_SMS_ID = 1;
243    private static final int MAX_SMS_RETRIEVE = 3;
244
245    /** Id for the back Calendar Loader */
246    private static final int LOADER_CALENDAR_ID = 2;
247    private static final String KEY_LOADER_EXTRA_EMAILS =
248            QuickContactActivity.class.getCanonicalName() + ".KEY_LOADER_EXTRA_EMAILS";
249    private static final int MAX_PAST_CALENDAR_RETRIEVE = 3;
250    private static final int MAX_FUTURE_CALENDAR_RETRIEVE = 3;
251    private static final long PAST_MILLISECOND_TO_SEARCH_LOCAL_CALENDAR =
252            180L * 24L * 60L * 60L * 1000L /* 180 days */;
253    private static final long FUTURE_MILLISECOND_TO_SEARCH_LOCAL_CALENDAR =
254            36L * 60L * 60L * 1000L /* 36 hours */;
255
256    /** Id for the background Call Log Loader */
257    private static final int LOADER_CALL_LOG_ID = 3;
258    private static final int MAX_CALL_LOG_RETRIEVE = 3;
259    private static final int MIN_NUM_CONTACT_ENTRIES_SHOWN = 3;
260    private static final int MIN_NUM_COLLAPSED_RECENT_ENTRIES_SHOWN = 3;
261    private static final int CARD_ENTRY_ID_EDIT_CONTACT = -2;
262
263
264    private static final int[] mRecentLoaderIds = new int[]{
265        LOADER_SMS_ID,
266        LOADER_CALENDAR_ID,
267        LOADER_CALL_LOG_ID};
268    private Map<Integer, List<ContactInteraction>> mRecentLoaderResults = new HashMap<>();
269
270    private static final String FRAGMENT_TAG_SELECT_ACCOUNT = "select_account_fragment";
271
272    final OnClickListener mEntryClickHandler = new OnClickListener() {
273        @Override
274        public void onClick(View v) {
275            // Data Id is stored as the entry view id
276            final int dataId = v.getId();
277            if (dataId == CARD_ENTRY_ID_EDIT_CONTACT) {
278                editContact();
279                return;
280            }
281            final Object intentObject = v.getTag();
282            if (intentObject == null || !(intentObject instanceof Intent)) {
283                Log.w(TAG, "Intent tag was not used correctly");
284                return;
285            }
286            final Intent intent = (Intent) intentObject;
287
288            // Default to USAGE_TYPE_CALL. Usage is summed among all types for sorting each data id
289            // so the exact usage type is not necessary in all cases
290            String usageType = DataUsageFeedback.USAGE_TYPE_CALL;
291
292            final String scheme = intent.getData().getScheme();
293            if ((scheme != null && scheme.equals(CallUtil.SCHEME_SMSTO)) ||
294                    (intent.getType() != null && intent.getType().equals(MIMETYPE_SMS))) {
295                usageType = DataUsageFeedback.USAGE_TYPE_SHORT_TEXT;
296            }
297
298            // Data IDs start at 1 so anything less is invalid
299            if (dataId > 0) {
300                final Uri uri = DataUsageFeedback.FEEDBACK_URI.buildUpon()
301                        .appendPath(String.valueOf(dataId))
302                        .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, usageType)
303                        .build();
304                final boolean successful = getContentResolver().update(
305                        uri, new ContentValues(), null, null) > 0;
306                if (!successful) {
307                    Log.w(TAG, "DataUsageFeedback increment failed");
308                }
309            } else {
310                Log.w(TAG, "Invalid Data ID");
311            }
312
313            startActivity(intent);
314        }
315    };
316
317    final ExpandingEntryCardViewListener mExpandingEntryCardViewListener
318            = new ExpandingEntryCardViewListener() {
319        @Override
320        public void onCollapse(int heightDelta) {
321            mScroller.prepareForShrinkingScrollChild(heightDelta);
322        }
323    };
324
325    /**
326     * Headless fragment used to handle account selection callbacks invoked from
327     * {@link DirectoryContactUtil}.
328     */
329    public static class SelectAccountDialogFragmentListener extends Fragment
330            implements SelectAccountDialogFragment.Listener {
331
332        private QuickContactActivity mQuickContactActivity;
333
334        public SelectAccountDialogFragmentListener() {}
335
336        @Override
337        public void onAccountChosen(AccountWithDataSet account, Bundle extraArgs) {
338            DirectoryContactUtil.createCopy(mQuickContactActivity.mContactData.getContentValues(),
339                    account, mQuickContactActivity);
340        }
341
342        @Override
343        public void onAccountSelectorCancelled() {}
344
345        /**
346         * Set the parent activity. Since rotation can cause this fragment to be used across
347         * more than one activity instance, we need to explicitly set this value instead
348         * of making this class non-static.
349         */
350        public void setQuickContactActivity(QuickContactActivity quickContactActivity) {
351            mQuickContactActivity = quickContactActivity;
352        }
353    }
354
355    final MultiShrinkScrollerListener mMultiShrinkScrollerListener
356            = new MultiShrinkScrollerListener() {
357        @Override
358        public void onScrolledOffBottom() {
359            if (!mIsWaitingForOtherPieceOfExitAnimation) {
360                finish();
361                return;
362            }
363            mIsWaitingForOtherPieceOfExitAnimation = false;
364        }
365
366        @Override
367        public void onEnterFullscreen() {
368            updateStatusBarColor();
369        }
370
371        @Override
372        public void onExitFullscreen() {
373            updateStatusBarColor();
374        }
375
376        @Override
377        public void onStartScrollOffBottom() {
378            // Remove the window shim now that we are starting an Activity exit animation.
379            final int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
380            final ObjectAnimator animator = ObjectAnimator.ofInt(mWindowScrim, "alpha", 0xFF, 0);
381            animator.addListener(mExitWindowShimAnimationListener);
382            animator.setDuration(duration).start();
383            mIsWaitingForOtherPieceOfExitAnimation = true;
384            mIsExitAnimationInProgress = true;
385        }
386    };
387
388    final AnimatorListener mExitWindowShimAnimationListener = new AnimatorListenerAdapter() {
389        @Override
390        public void onAnimationEnd(Animator animation) {
391            if (!mIsWaitingForOtherPieceOfExitAnimation) {
392                finish();
393                return;
394            }
395            mIsWaitingForOtherPieceOfExitAnimation = false;
396        }
397    };
398
399
400    /**
401     * Data items are compared to the same mimetype based off of three qualities:
402     * 1. Super primary
403     * 2. Primary
404     * 3. Times used
405     */
406    private final Comparator<DataItem> mWithinMimeTypeDataItemComparator =
407            new Comparator<DataItem>() {
408        @Override
409        public int compare(DataItem lhs, DataItem rhs) {
410            if (!lhs.getMimeType().equals(rhs.getMimeType())) {
411                Log.wtf(TAG, "Comparing DataItems with different mimetypes lhs.getMimeType(): " +
412                        lhs.getMimeType() + " rhs.getMimeType(): " + rhs.getMimeType());
413                return 0;
414            }
415
416            if (lhs.isSuperPrimary()) {
417                return -1;
418            } else if (rhs.isSuperPrimary()) {
419                return 1;
420            } else if (lhs.isPrimary() && !rhs.isPrimary()) {
421                return -1;
422            } else if (!lhs.isPrimary() && rhs.isPrimary()) {
423                return 1;
424            } else {
425                final int lhsTimesUsed =
426                        lhs.getTimesUsed() == null ? 0 : lhs.getTimesUsed();
427                final int rhsTimesUsed =
428                        rhs.getTimesUsed() == null ? 0 : rhs.getTimesUsed();
429
430                return rhsTimesUsed - lhsTimesUsed;
431            }
432        }
433    };
434
435    /**
436     * Sorts among different mimetypes based off:
437     * 1. Times used
438     * 2. Last time used
439     * 3. Statically defined
440     */
441    private final Comparator<List<DataItem>> mAmongstMimeTypeDataItemComparator =
442            new Comparator<List<DataItem>> () {
443        @Override
444        public int compare(List<DataItem> lhsList, List<DataItem> rhsList) {
445            DataItem lhs = lhsList.get(0);
446            DataItem rhs = rhsList.get(0);
447            final int lhsTimesUsed = lhs.getTimesUsed() == null ? 0 : lhs.getTimesUsed();
448            final int rhsTimesUsed = rhs.getTimesUsed() == null ? 0 : rhs.getTimesUsed();
449            final int timesUsedDifference = rhsTimesUsed - lhsTimesUsed;
450            if (timesUsedDifference != 0) {
451                return timesUsedDifference;
452            }
453
454            final long lhsLastTimeUsed =
455                    lhs.getLastTimeUsed() == null ? 0 : lhs.getLastTimeUsed();
456            final long rhsLastTimeUsed =
457                    rhs.getLastTimeUsed() == null ? 0 : rhs.getLastTimeUsed();
458            final long lastTimeUsedDifference = rhsLastTimeUsed - lhsLastTimeUsed;
459            if (lastTimeUsedDifference > 0) {
460                return 1;
461            } else if (lastTimeUsedDifference < 0) {
462                return -1;
463            }
464
465            // Times used and last time used are the same. Resort to statically defined.
466            final String lhsMimeType = lhs.getMimeType();
467            final String rhsMimeType = rhs.getMimeType();
468            for (String mimeType : LEADING_MIMETYPES) {
469                if (lhsMimeType.equals(mimeType)) {
470                    return -1;
471                } else if (rhsMimeType.equals(mimeType)) {
472                    return 1;
473                }
474            }
475            return 0;
476        }
477    };
478
479    @Override
480    protected void onCreate(Bundle savedInstanceState) {
481        Trace.beginSection("onCreate()");
482        super.onCreate(savedInstanceState);
483
484        getWindow().setStatusBarColor(Color.TRANSPARENT);
485
486        processIntent(getIntent());
487
488        // Show QuickContact in front of soft input
489        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
490                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
491
492        setContentView(R.layout.quickcontact_activity);
493
494        mMaterialColorMapUtils = new MaterialColorMapUtils(getResources());
495
496        mContactCard = (ExpandingEntryCardView) findViewById(R.id.communication_card);
497        mNoContactDetailsCard = (ExpandingEntryCardView) findViewById(R.id.no_contact_data_card);
498        mRecentCard = (ExpandingEntryCardView) findViewById(R.id.recent_card);
499        mAboutCard = (ExpandingEntryCardView) findViewById(R.id.about_card);
500        mScroller = (MultiShrinkScroller) findViewById(R.id.multiscroller);
501
502        mNoContactDetailsCard.setOnClickListener(mEntryClickHandler);
503        mContactCard.setOnClickListener(mEntryClickHandler);
504        mContactCard.setExpandButtonText(
505        getResources().getString(R.string.expanding_entry_card_view_see_all));
506
507        mRecentCard.setOnClickListener(mEntryClickHandler);
508        mRecentCard.setTitle(getResources().getString(R.string.recent_card_title));
509
510        mAboutCard.setOnClickListener(mEntryClickHandler);
511
512        mPhotoView = (ImageView) findViewById(R.id.photo);
513        mTransparentView = findViewById(R.id.transparent_view);
514        if (mScroller != null) {
515            mTransparentView.setOnClickListener(new OnClickListener() {
516                @Override
517                public void onClick(View v) {
518                    mScroller.scrollOffBottom();
519                }
520            });
521        }
522
523        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
524        setActionBar(toolbar);
525        getActionBar().setTitle(null);
526        // Put a TextView with a known resource id into the ActionBar. This allows us to easily
527        // find the correct TextView location & size later.
528        toolbar.addView(getLayoutInflater().inflate(R.layout.quickcontact_title_placeholder, null));
529
530        mHasAlreadyBeenOpened = savedInstanceState != null;
531
532        mWindowScrim = new ColorDrawable(SCRIM_COLOR);
533        getWindow().setBackgroundDrawable(mWindowScrim);
534        if (!mHasAlreadyBeenOpened) {
535            final int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
536            ObjectAnimator.ofInt(mWindowScrim, "alpha", 0, 0xFF).setDuration(duration).start();
537        }
538
539        mScroller.initialize(mMultiShrinkScrollerListener, mExtraMode == MODE_FULLY_EXPANDED);
540        // mScroller needs to perform asynchronous measurements after initalize(), therefore
541        // we can't mark this as GONE.
542        mScroller.setVisibility(View.INVISIBLE);
543
544        setHeaderNameText(R.string.missing_name);
545
546        mSelectAccountFragmentListener= (SelectAccountDialogFragmentListener) getFragmentManager()
547                .findFragmentByTag(FRAGMENT_TAG_SELECT_ACCOUNT);
548        if (mSelectAccountFragmentListener == null) {
549            mSelectAccountFragmentListener = new SelectAccountDialogFragmentListener();
550            getFragmentManager().beginTransaction().add(0, mSelectAccountFragmentListener,
551                    FRAGMENT_TAG_SELECT_ACCOUNT).commit();
552            mSelectAccountFragmentListener.setRetainInstance(true);
553        }
554        mSelectAccountFragmentListener.setQuickContactActivity(this);
555
556        if (savedInstanceState != null) {
557            final int color = savedInstanceState.getInt(KEY_THEME_COLOR, 0);
558            SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ false,
559                    new Runnable() {
560                        @Override
561                        public void run() {
562                            // Need to wait for the pre draw before setting the initial scroll
563                            // value. Prior to pre draw all scroll values are invalid.
564                            if (mHasAlreadyBeenOpened) {
565                                mScroller.setVisibility(View.VISIBLE);
566                                mScroller.setScroll(mScroller.getScrollNeededToBeFullScreen());
567                            }
568                            // Need to wait for pre draw for setting the theme color. Setting the
569                            // header tint before the MultiShrinkScroller has been measured will
570                            // cause incorrect tinting calculations.
571                            if (color != 0) {
572                                setThemeColor(mMaterialColorMapUtils
573                                        .calculatePrimaryAndSecondaryColor(color));
574                            }
575                        }
576                    });
577        }
578
579        Trace.endSection();
580    }
581
582    @Override
583    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
584        if (requestCode == REQUEST_CODE_CONTACT_EDITOR_ACTIVITY &&
585                resultCode == ContactDeletionInteraction.RESULT_CODE_DELETED) {
586            // The contact that we were showing has been deleted.
587            finish();
588        }
589    }
590
591    @Override
592    protected void onNewIntent(Intent intent) {
593        super.onNewIntent(intent);
594        mHasAlreadyBeenOpened = true;
595        mHasComputedThemeColor = false;
596        processIntent(intent);
597    }
598
599    @Override
600    public void onSaveInstanceState(Bundle savedInstanceState) {
601        super.onSaveInstanceState(savedInstanceState);
602        if (mColorFilter != null) {
603            savedInstanceState.putInt(KEY_THEME_COLOR, mColorFilter.getColor());
604        }
605    }
606
607    private void processIntent(Intent intent) {
608        Uri lookupUri = intent.getData();
609
610        // Check to see whether it comes from the old version.
611        if (lookupUri != null && LEGACY_AUTHORITY.equals(lookupUri.getAuthority())) {
612            final long rawContactId = ContentUris.parseId(lookupUri);
613            lookupUri = RawContacts.getContactLookupUri(getContentResolver(),
614                    ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
615        }
616        mExtraMode = getIntent().getIntExtra(QuickContact.EXTRA_MODE,
617                QuickContact.MODE_LARGE);
618        final Uri oldLookupUri = mLookupUri;
619
620        mLookupUri = Preconditions.checkNotNull(lookupUri, "missing lookupUri");
621        mExcludeMimes = intent.getStringArrayExtra(QuickContact.EXTRA_EXCLUDE_MIMES);
622        if (oldLookupUri == null) {
623            mContactLoader = (ContactLoader) getLoaderManager().initLoader(
624                    LOADER_CONTACT_ID, null, mLoaderContactCallbacks);
625        } else if (oldLookupUri != mLookupUri) {
626            // After copying a directory contact, the contact URI changes. Therefore,
627            // we need to restart the loader and reload the new contact.
628            for (int interactionLoaderId : mRecentLoaderIds) {
629                getLoaderManager().destroyLoader(interactionLoaderId);
630            }
631            mContactLoader = (ContactLoader) getLoaderManager().restartLoader(
632                    LOADER_CONTACT_ID, null, mLoaderContactCallbacks);
633        }
634
635        NfcHandler.register(this, mLookupUri);
636    }
637
638    private void runEntranceAnimation() {
639        if (mHasAlreadyBeenOpened) {
640            return;
641        }
642        mHasAlreadyBeenOpened = true;
643        mScroller.scrollUpForEntranceAnimation(mExtraMode != MODE_FULLY_EXPANDED);
644    }
645
646    /** Assign this string to the view if it is not empty. */
647    private void setHeaderNameText(int resId) {
648        if (mScroller != null) {
649            mScroller.setTitle(getText(resId) == null ? null : getText(resId).toString());
650        }
651    }
652
653    /** Assign this string to the view if it is not empty. */
654    private void setHeaderNameText(String value) {
655        if (!TextUtils.isEmpty(value)) {
656            if (mScroller != null) {
657                mScroller.setTitle(value);
658            }
659        }
660    }
661
662    /**
663     * Check if the given MIME-type appears in the list of excluded MIME-types
664     * that the most-recent caller requested.
665     */
666    private boolean isMimeExcluded(String mimeType) {
667        if (mExcludeMimes == null) return false;
668        for (String excludedMime : mExcludeMimes) {
669            if (TextUtils.equals(excludedMime, mimeType)) {
670                return true;
671            }
672        }
673        return false;
674    }
675
676    /**
677     * Handle the result from the ContactLoader
678     */
679    private void bindContactData(final Contact data) {
680        Trace.beginSection("bindContactData");
681        mContactData = data;
682        invalidateOptionsMenu();
683
684        Trace.endSection();
685        Trace.beginSection("Set display photo & name");
686
687        mPhotoSetter.setupContactPhoto(data, mPhotoView);
688        extractAndApplyTintFromPhotoViewAsynchronously();
689        analyzeWhitenessOfPhotoAsynchronously();
690        setHeaderNameText(data.getDisplayName());
691
692        Trace.endSection();
693
694        mEntriesAndActionsTask = new AsyncTask<Void, Void,
695                Pair<List<List<DataItem>>, Map<String, List<DataItem>>>>() {
696
697            @Override
698            protected Pair<List<List<DataItem>>, Map<String, List<DataItem>>> doInBackground(
699                    Void... params) {
700                return generateDataModelFromContact(data);
701            }
702
703            @Override
704            protected void onPostExecute(Pair<List<List<DataItem>>,
705                    Map<String, List<DataItem>>> dataItemsPair) {
706                super.onPostExecute(dataItemsPair);
707                mDataItemsList = dataItemsPair.first;
708                mDataItemsMap = dataItemsPair.second;
709                // Check that original AsyncTask parameters are still valid and the activity
710                // is still running before binding to UI. A new intent could invalidate
711                // the results, for example.
712                if (data == mContactData && !isCancelled()) {
713                    bindDataToCards();
714                    showActivity();
715                }
716            }
717        };
718        mEntriesAndActionsTask.execute();
719    }
720
721    private void bindDataToCards() {
722        startInteractionLoaders();
723        populateContactAndAboutCard();
724    }
725
726    private void startInteractionLoaders() {
727        final List<DataItem> phoneDataItems = mDataItemsMap.get(Phone.CONTENT_ITEM_TYPE);
728        String[] phoneNumbers = null;
729        if (phoneDataItems != null) {
730            phoneNumbers = new String[phoneDataItems.size()];
731            for (int i = 0; i < phoneDataItems.size(); ++i) {
732                phoneNumbers[i] = ((PhoneDataItem) phoneDataItems.get(i)).getNumber();
733            }
734        }
735        final Bundle phonesExtraBundle = new Bundle();
736        phonesExtraBundle.putStringArray(KEY_LOADER_EXTRA_PHONES, phoneNumbers);
737
738        Trace.beginSection("start sms loader");
739        getLoaderManager().initLoader(
740                LOADER_SMS_ID,
741                phonesExtraBundle,
742                mLoaderInteractionsCallbacks);
743        Trace.endSection();
744
745        Trace.beginSection("start call log loader");
746        getLoaderManager().initLoader(
747                LOADER_CALL_LOG_ID,
748                phonesExtraBundle,
749                mLoaderInteractionsCallbacks);
750        Trace.endSection();
751
752
753        Trace.beginSection("start calendar loader");
754        final List<DataItem> emailDataItems = mDataItemsMap.get(Email.CONTENT_ITEM_TYPE);
755        String[] emailAddresses = null;
756        if (emailDataItems != null) {
757            emailAddresses = new String[emailDataItems.size()];
758            for (int i = 0; i < emailDataItems.size(); ++i) {
759                emailAddresses[i] = ((EmailDataItem) emailDataItems.get(i)).getAddress();
760            }
761        }
762        final Bundle emailsExtraBundle = new Bundle();
763        emailsExtraBundle.putStringArray(KEY_LOADER_EXTRA_EMAILS, emailAddresses);
764        getLoaderManager().initLoader(
765                LOADER_CALENDAR_ID,
766                emailsExtraBundle,
767                mLoaderInteractionsCallbacks);
768        Trace.endSection();
769    }
770
771    private void showActivity() {
772        if (mScroller != null) {
773            mScroller.setVisibility(View.VISIBLE);
774            SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ false,
775                    new Runnable() {
776                        @Override
777                        public void run() {
778                            runEntranceAnimation();
779                        }
780                    });
781        }
782    }
783
784    private void populateContactAndAboutCard() {
785        Trace.beginSection("bind contact card");
786
787        final List<List<Entry>> contactCardEntries = new ArrayList<>();
788        final List<List<Entry>> aboutCardEntries = new ArrayList<>();
789
790        for (int i = 0; i < mDataItemsList.size(); ++i) {
791            final List<DataItem> dataItemsByMimeType = mDataItemsList.get(i);
792            final DataItem topDataItem = dataItemsByMimeType.get(0);
793            if (ABOUT_CARD_MIMETYPES.contains(topDataItem.getMimeType())) {
794                List<Entry> aboutEntries = dataItemsToEntries(mDataItemsList.get(i));
795                if (aboutEntries.size() > 0) {
796                    aboutCardEntries.add(aboutEntries);
797                }
798            } else {
799                List<Entry> contactEntries = dataItemsToEntries(mDataItemsList.get(i));
800                if (contactEntries.size() > 0) {
801                    contactCardEntries.add(contactEntries);
802                }
803            }
804        }
805
806        if (contactCardEntries.size() > 0) {
807            mContactCard.initialize(contactCardEntries,
808                    /* numInitialVisibleEntries = */ MIN_NUM_CONTACT_ENTRIES_SHOWN,
809                    /* isExpanded = */ false,
810                    mExpandingEntryCardViewListener);
811            mContactCard.setVisibility(View.VISIBLE);
812        } else {
813            mContactCard.setVisibility(View.GONE);
814        }
815        Trace.endSection();
816
817        Trace.beginSection("bind about card");
818        mAboutCard.initialize(aboutCardEntries,
819                /* numInitialVisibleEntries = */ 1,
820                /* isExpanded = */ true,
821                mExpandingEntryCardViewListener);
822
823        if (contactCardEntries.size() == 0 && aboutCardEntries.size() == 0) {
824            initializeNoContactDetailCard();
825        } else {
826            mNoContactDetailsCard.setVisibility(View.GONE);
827        }
828
829        // If the Recent card is already initialized (all recent data is loaded), show the About
830        // card if it has entries. Otherwise About card visibility will be set in bindRecentData()
831        if (isAllRecentDataLoaded() && aboutCardEntries.size() > 0) {
832            mAboutCard.setVisibility(View.VISIBLE);
833        }
834        Trace.endSection();
835    }
836
837    /**
838     * Create a card that shows "Add email" and "Add phone number" entries in grey.
839     */
840    private void initializeNoContactDetailCard() {
841        final Drawable phoneIcon = getResources().getDrawable(
842                R.drawable.ic_phone_24dp).mutate();
843        final Entry phonePromptEntry = new Entry(CARD_ENTRY_ID_EDIT_CONTACT,
844                phoneIcon, getString(R.string.quickcontact_add_phone_number),
845                /* subHeader = */ null, /* text = */ null, getEditContactIntent(),
846                /* alternateIcon = */ null, /* alternateIntent = */ null,
847                /* alternateContentDescription = */ null, /* shouldApplyColor = */ true,
848                /* isEditable = */ false);
849
850        final Drawable emailIcon = getResources().getDrawable(
851                R.drawable.ic_email_24dp).mutate();
852        final Entry emailPromptEntry = new Entry(CARD_ENTRY_ID_EDIT_CONTACT,
853                emailIcon, getString(R.string.quickcontact_add_email), /* subHeader = */ null,
854                /* text = */ null, getEditContactIntent(), /* alternateIcon = */ null,
855                /* alternateIntent = */ null, /* alternateContentDescription = */ null,
856                /* shouldApplyColor = */ true, /* isEditable = */ false);
857
858        final List<List<Entry>> promptEntries = new ArrayList<>();
859        promptEntries.add(new ArrayList<Entry>(1));
860        promptEntries.add(new ArrayList<Entry>(1));
861        promptEntries.get(0).add(phonePromptEntry);
862        promptEntries.get(1).add(emailPromptEntry);
863
864        final int subHeaderTextColor = getResources().getColor(
865                R.color.quickcontact_entry_sub_header_text_color);
866        final PorterDuffColorFilter greyColorFilter =
867                new PorterDuffColorFilter(subHeaderTextColor, PorterDuff.Mode.SRC_ATOP);
868        mNoContactDetailsCard.initialize(promptEntries, 2, /* isExpanded = */ false,
869                mExpandingEntryCardViewListener);
870        mNoContactDetailsCard.setVisibility(View.VISIBLE);
871        mNoContactDetailsCard.setEntryHeaderColor(subHeaderTextColor);
872        mNoContactDetailsCard.setColorAndFilter(subHeaderTextColor, greyColorFilter);
873    }
874
875    /**
876     * Builds the {@link DataItem}s Map out of the Contact.
877     * @param data The contact to build the data from.
878     * @return A pair containing a list of data items sorted within mimetype and sorted
879     *  amongst mimetype. The map goes from mimetype string to the sorted list of data items within
880     *  mimetype
881     */
882    private Pair<List<List<DataItem>>, Map<String, List<DataItem>>> generateDataModelFromContact(
883            Contact data) {
884        Trace.beginSection("Build data items map");
885
886        final Map<String, List<DataItem>> dataItemsMap = new HashMap<>();
887
888        final ResolveCache cache = ResolveCache.getInstance(this);
889        for (RawContact rawContact : data.getRawContacts()) {
890            for (DataItem dataItem : rawContact.getDataItems()) {
891                dataItem.setRawContactId(rawContact.getId());
892
893                final String mimeType = dataItem.getMimeType();
894                if (mimeType == null) continue;
895
896                final AccountType accountType = rawContact.getAccountType(this);
897                final DataKind dataKind = AccountTypeManager.getInstance(this)
898                        .getKindOrFallback(accountType, mimeType);
899                if (dataKind == null) continue;
900
901                dataItem.setDataKind(dataKind);
902
903                final boolean hasData = !TextUtils.isEmpty(dataItem.buildDataString(this,
904                        dataKind));
905
906                if (isMimeExcluded(mimeType) || !hasData) continue;
907
908                List<DataItem> dataItemListByType = dataItemsMap.get(mimeType);
909                if (dataItemListByType == null) {
910                    dataItemListByType = new ArrayList<>();
911                    dataItemsMap.put(mimeType, dataItemListByType);
912                }
913                dataItemListByType.add(dataItem);
914            }
915        }
916        Trace.endSection();
917
918        Trace.beginSection("sort within mimetypes");
919        /*
920         * Sorting is a multi part step. The end result is to a have a sorted list of the most
921         * used data items, one per mimetype. Then, within each mimetype, the list of data items
922         * for that type is also sorted, based off of {super primary, primary, times used} in that
923         * order.
924         */
925        final List<List<DataItem>> dataItemsList = new ArrayList<>();
926        for (List<DataItem> mimeTypeDataItems : dataItemsMap.values()) {
927            // Remove duplicate data items
928            Collapser.collapseList(mimeTypeDataItems, this);
929            // Sort within mimetype
930            Collections.sort(mimeTypeDataItems, mWithinMimeTypeDataItemComparator);
931            // Add to the list of data item lists
932            dataItemsList.add(mimeTypeDataItems);
933        }
934        Trace.endSection();
935
936        Trace.beginSection("sort amongst mimetypes");
937        // Sort amongst mimetypes to bubble up the top data items for the contact card
938        Collections.sort(dataItemsList, mAmongstMimeTypeDataItemComparator);
939        Trace.endSection();
940
941        return new Pair<>(dataItemsList, dataItemsMap);
942    }
943
944    /**
945     * Converts a {@link DataItem} into an {@link ExpandingEntryCardView.Entry} for display.
946     * If the {@link ExpandingEntryCardView.Entry} has no visual elements, null is returned.
947     * @param dataItem The {@link DataItem} to convert.
948     * @return The {@link ExpandingEntryCardView.Entry}, or null if no visual elements are present.
949     */
950    private Entry dataItemToEntry(DataItem dataItem) {
951        Drawable icon = null;
952        String header = null;
953        String subHeader = null;
954        Drawable subHeaderIcon = null;
955        String text = null;
956        Drawable textIcon = null;
957        Intent intent = null;
958        boolean shouldApplyColor = true;
959        Drawable alternateIcon = null;
960        Intent alternateIntent = null;
961        String alternateContentDescription = null;
962        final boolean isEditable = false;
963
964        DataKind kind = dataItem.getDataKind();
965
966        if (dataItem instanceof ImDataItem) {
967            final ImDataItem im = (ImDataItem) dataItem;
968            intent = ContactsUtils.buildImIntent(this, im).first;
969            header = getResources().getString(R.string.header_im_entry);
970            final boolean isEmail = im.isCreatedFromEmail();
971            final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
972            subHeader = Im.getProtocolLabel(getResources(), protocol,
973                    im.getCustomProtocol()).toString();
974        } else if (dataItem instanceof OrganizationDataItem) {
975            final OrganizationDataItem organization = (OrganizationDataItem) dataItem;
976            header = getResources().getString(R.string.header_organization_entry);
977            subHeader = organization.getCompany();
978            text = organization.getTitle();
979        } else if (dataItem instanceof NicknameDataItem) {
980            final NicknameDataItem nickname = (NicknameDataItem) dataItem;
981            // Build nickname entries
982            final boolean isNameRawContact =
983                (mContactData.getNameRawContactId() == dataItem.getRawContactId());
984
985            final boolean duplicatesTitle =
986                isNameRawContact
987                && mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;
988
989            if (!duplicatesTitle) {
990                header = getResources().getString(R.string.header_nickname_entry);
991                subHeader = nickname.getName();
992            }
993        } else if (dataItem instanceof NoteDataItem) {
994            final NoteDataItem note = (NoteDataItem) dataItem;
995            header = getResources().getString(R.string.header_note_entry);
996            subHeader = note.getNote();
997        } else if (dataItem instanceof WebsiteDataItem) {
998            final WebsiteDataItem website = (WebsiteDataItem) dataItem;
999            header = getResources().getString(R.string.header_website_entry);
1000            subHeader = website.getUrl();
1001            try {
1002                final WebAddress webAddress = new WebAddress(website.buildDataString(this, kind));
1003                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString()));
1004            } catch (final ParseException e) {
1005                Log.e(TAG, "Couldn't parse website: " + website.buildDataString(this, kind));
1006            }
1007        } else if (dataItem instanceof EventDataItem) {
1008            final EventDataItem event = (EventDataItem) dataItem;
1009            final String dataString = event.buildDataString(this, kind);
1010            final Calendar cal = DateUtils.parseDate(dataString, false);
1011            if (cal != null) {
1012                final Date nextAnniversary =
1013                        DateUtils.getNextAnnualDate(cal);
1014                final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
1015                builder.appendPath("time");
1016                ContentUris.appendId(builder, nextAnniversary.getTime());
1017                intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
1018            }
1019            header = getResources().getString(R.string.header_event_entry);
1020            if (event.hasKindTypeColumn(kind)) {
1021                subHeader = getResources().getString(Event.getTypeResource(
1022                        event.getKindTypeColumn(kind)));
1023            }
1024            text = DateUtils.formatDate(this, dataString);
1025        } else if (dataItem instanceof RelationDataItem) {
1026            final RelationDataItem relation = (RelationDataItem) dataItem;
1027            final String dataString = relation.buildDataString(this, kind);
1028            if (!TextUtils.isEmpty(dataString)) {
1029                intent = new Intent(Intent.ACTION_SEARCH);
1030                intent.putExtra(SearchManager.QUERY, dataString);
1031                intent.setType(Contacts.CONTENT_TYPE);
1032            }
1033            header = getResources().getString(R.string.header_relation_entry);
1034            subHeader = relation.getName();
1035            if (relation.hasKindTypeColumn(kind)) {
1036                text = Relation.getTypeLabel(getResources(), relation.getKindTypeColumn(kind),
1037                        relation.getLabel()).toString();
1038            }
1039        } else if (dataItem instanceof PhoneDataItem) {
1040            final PhoneDataItem phone = (PhoneDataItem) dataItem;
1041            if (!TextUtils.isEmpty(phone.getNumber())) {
1042                header = phone.buildDataString(this, kind);
1043                if (phone.hasKindTypeColumn(kind)) {
1044                    text = Phone.getTypeLabel(getResources(), phone.getKindTypeColumn(kind),
1045                            phone.getLabel()).toString();
1046                }
1047                icon = getResources().getDrawable(R.drawable.ic_phone_24dp);
1048                if (PhoneCapabilityTester.isPhone(this)) {
1049                    intent = CallUtil.getCallIntent(phone.getNumber());
1050                }
1051                alternateIntent = new Intent(Intent.ACTION_SENDTO,
1052                        Uri.fromParts(CallUtil.SCHEME_SMSTO, phone.getNumber(), null));
1053                alternateIcon = getResources().getDrawable(R.drawable.ic_message_24dp);
1054                alternateContentDescription = getResources().getString(R.string.sms_other);
1055            }
1056        } else if (dataItem instanceof EmailDataItem) {
1057            final EmailDataItem email = (EmailDataItem) dataItem;
1058            final String address = email.getData();
1059            if (!TextUtils.isEmpty(address)) {
1060                final Uri mailUri = Uri.fromParts(CallUtil.SCHEME_MAILTO, address, null);
1061                intent = new Intent(Intent.ACTION_SENDTO, mailUri);
1062                header = email.getAddress();
1063                if (email.hasKindTypeColumn(kind)) {
1064                    text = Email.getTypeLabel(getResources(), email.getKindTypeColumn(kind),
1065                            email.getLabel()).toString();
1066                }
1067                icon = getResources().getDrawable(R.drawable.ic_email_24dp);
1068            }
1069        } else if (dataItem instanceof StructuredPostalDataItem) {
1070            StructuredPostalDataItem postal = (StructuredPostalDataItem) dataItem;
1071            final String postalAddress = postal.getFormattedAddress();
1072            if (!TextUtils.isEmpty(postalAddress)) {
1073                intent = StructuredPostalUtils.getViewPostalAddressIntent(postalAddress);
1074                header = postal.getFormattedAddress();
1075                if (postal.hasKindTypeColumn(kind)) {
1076                    text = StructuredPostal.getTypeLabel(getResources(),
1077                            postal.getKindTypeColumn(kind), postal.getLabel()).toString();
1078                }
1079                icon = getResources().getDrawable(R.drawable.ic_place_24dp);
1080            }
1081        } else if (dataItem instanceof SipAddressDataItem) {
1082            if (PhoneCapabilityTester.isSipPhone(this)) {
1083                final SipAddressDataItem sip = (SipAddressDataItem) dataItem;
1084                final String address = sip.getSipAddress();
1085                if (!TextUtils.isEmpty(address)) {
1086                    final Uri callUri = Uri.fromParts(CallUtil.SCHEME_SIP, address, null);
1087                    intent = CallUtil.getCallIntent(callUri);
1088                    // Note that this item will get a SIP-specific variant
1089                    // of the "call phone" icon, rather than the standard
1090                    // app icon for the Phone app (which we show for
1091                    // regular phone numbers.)  That's because the phone
1092                    // app explicitly specifies an android:icon attribute
1093                    // for the SIP-related intent-filters in its manifest.
1094                }
1095                icon = ResolveCache.getInstance(this).getIcon(sip.getMimeType(), intent);
1096                // Call mutate to create a new Drawable.ConstantState for color filtering
1097                if (icon != null) {
1098                    icon.mutate();
1099                }
1100            }
1101        } else if (dataItem instanceof StructuredNameDataItem) {
1102            final String givenName = ((StructuredNameDataItem) dataItem).getGivenName();
1103            if (!TextUtils.isEmpty(givenName)) {
1104                mAboutCard.setTitle(getResources().getString(R.string.about_card_title) +
1105                        " " + givenName);
1106            } else {
1107                mAboutCard.setTitle(getResources().getString(R.string.about_card_title));
1108            }
1109        } else {
1110            // Custom DataItem
1111            header = dataItem.buildDataStringForDisplay(this, kind);
1112            text = kind.typeColumn;
1113            intent = new Intent(Intent.ACTION_VIEW);
1114            final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataItem.getId());
1115            intent.setDataAndType(uri, dataItem.getMimeType());
1116
1117            if (intent != null) {
1118                final String mimetype = intent.getType();
1119
1120                // Attempt to use known icons for known 3p types. Otherwise default to ResolveCache
1121                switch (mimetype) {
1122                    case MIMETYPE_GPLUS_PROFILE:
1123                        if (INTENT_DATA_GPLUS_PROFILE_ADD_TO_CIRCLE.equals(
1124                                intent.getDataString())) {
1125                            icon = getResources().getDrawable(
1126                                    R.drawable.ic_add_to_circles_black_24);
1127                        } else {
1128                            icon = getResources().getDrawable(R.drawable.ic_google_plus_24dp);
1129                        }
1130                        break;
1131                    case MIMETYPE_HANGOUTS:
1132                        if (INTENT_DATA_HANGOUTS_VIDEO.equals(intent.getDataString())) {
1133                            icon = getResources().getDrawable(R.drawable.ic_hangout_video_24dp);
1134                        } else {
1135                            icon = getResources().getDrawable(R.drawable.ic_hangout_24dp);
1136                        }
1137                        break;
1138                    default:
1139                        icon = ResolveCache.getInstance(this).getIcon(
1140                                dataItem.getMimeType(), intent);
1141                        // Call mutate to create a new Drawable.ConstantState for color filtering
1142                        if (icon != null) {
1143                            icon.mutate();
1144                        }
1145                        shouldApplyColor = false;
1146                }
1147            }
1148        }
1149
1150        if (intent != null) {
1151            // Do not set the intent is there are no resolves
1152            if (!PhoneCapabilityTester.isIntentRegistered(this, intent)) {
1153                intent = null;
1154            }
1155        }
1156
1157        if (alternateIntent != null) {
1158            // Do not set the alternate intent is there are no resolves
1159            if (!PhoneCapabilityTester.isIntentRegistered(this, alternateIntent)) {
1160                alternateIntent = null;
1161            }
1162
1163            // Attempt to use package manager to find a suitable content description if needed
1164            if (TextUtils.isEmpty(alternateContentDescription)) {
1165                alternateContentDescription = getIntentResolveLabel(alternateIntent);
1166            }
1167        }
1168
1169        // If the Entry has no visual elements, return null
1170        if (icon == null && TextUtils.isEmpty(header) && TextUtils.isEmpty(subHeader) &&
1171                subHeaderIcon == null && TextUtils.isEmpty(text) && textIcon == null) {
1172            return null;
1173        }
1174
1175        final int dataId = dataItem.getId() > Integer.MAX_VALUE ?
1176                -1 : (int) dataItem.getId();
1177
1178        return new Entry(dataId, icon, header, subHeader, subHeaderIcon, text, textIcon, intent,
1179                alternateIcon, alternateIntent, alternateContentDescription, shouldApplyColor,
1180                isEditable);
1181    }
1182
1183    private List<Entry> dataItemsToEntries(List<DataItem> dataItems) {
1184        final List<Entry> entries = new ArrayList<>();
1185        for (DataItem dataItem : dataItems) {
1186            final Entry entry = dataItemToEntry(dataItem);
1187            if (entry != null) {
1188                entries.add(entry);
1189            }
1190        }
1191        return entries;
1192    }
1193
1194    private String getIntentResolveLabel(Intent intent) {
1195        final List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent,
1196                PackageManager.MATCH_DEFAULT_ONLY);
1197
1198        // Pick first match, otherwise best found
1199        ResolveInfo bestResolve = null;
1200        final int size = matches.size();
1201        if (size == 1) {
1202            bestResolve = matches.get(0);
1203        } else if (size > 1) {
1204            bestResolve = ResolveCache.getInstance(this).getBestResolve(intent, matches);
1205        }
1206
1207        if (bestResolve == null) {
1208            return null;
1209        }
1210
1211        return String.valueOf(bestResolve.loadLabel(getPackageManager()));
1212    }
1213
1214    /**
1215     * Asynchronously extract the most vibrant color from the PhotoView. Once extracted,
1216     * apply this tint to {@link MultiShrinkScroller}. This operation takes about 20-30ms
1217     * on a Nexus 5.
1218     */
1219    private void extractAndApplyTintFromPhotoViewAsynchronously() {
1220        if (mScroller == null) {
1221            return;
1222        }
1223        final Drawable imageViewDrawable = mPhotoView.getDrawable();
1224        new AsyncTask<Void, Void, MaterialPalette>() {
1225            @Override
1226            protected MaterialPalette doInBackground(Void... params) {
1227
1228                if (imageViewDrawable instanceof BitmapDrawable) {
1229                    final Bitmap bitmap = ((BitmapDrawable) imageViewDrawable).getBitmap();
1230                    final int primaryColor = colorFromBitmap(bitmap);
1231                    if (primaryColor != 0) {
1232                        return mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(
1233                                primaryColor);
1234                    }
1235                }
1236                if (imageViewDrawable instanceof LetterTileDrawable) {
1237                    final int primaryColor = ((LetterTileDrawable) imageViewDrawable).getColor();
1238                    return mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(primaryColor);
1239                }
1240                return MaterialColorMapUtils.getDefaultPrimaryAndSecondaryColors(getResources());
1241            }
1242
1243            @Override
1244            protected void onPostExecute(MaterialPalette palette) {
1245                super.onPostExecute(palette);
1246                if (mHasComputedThemeColor) {
1247                    // If we had previously computed a theme color from the contact photo,
1248                    // then do not update the theme color. Changing the theme color several
1249                    // seconds after QC has started, as a result of an updated/upgraded photo,
1250                    // is a jarring experience. On the other hand, changing the theme color after
1251                    // a rotation or onNewIntent() is perfectly fine.
1252                    return;
1253                }
1254                // Check that the Photo has not changed. If it has changed, the new tint
1255                // color needs to be extracted
1256                if (imageViewDrawable == mPhotoView.getDrawable()) {
1257                    mHasComputedThemeColor = true;
1258                    setThemeColor(palette);
1259                }
1260            }
1261        }.execute();
1262    }
1263
1264    /**
1265     * Examine how many white pixels are in the bitmap in order to determine whether or not
1266     * we need gradient overlays on top of the image.
1267     */
1268    private void analyzeWhitenessOfPhotoAsynchronously() {
1269        final Drawable imageViewDrawable = mPhotoView.getDrawable();
1270        new AsyncTask<Void, Void, Boolean>() {
1271            @Override
1272            protected Boolean doInBackground(Void... params) {
1273                if (imageViewDrawable instanceof BitmapDrawable) {
1274                    final Bitmap bitmap = ((BitmapDrawable) imageViewDrawable).getBitmap();
1275                    return WhitenessUtils.isBitmapWhiteAtTopOrBottom(bitmap);
1276                }
1277                return !(imageViewDrawable instanceof LetterTileDrawable);
1278            }
1279
1280            @Override
1281            protected void onPostExecute(Boolean isWhite) {
1282                super.onPostExecute(isWhite);
1283                mScroller.setUseGradient(isWhite);
1284            }
1285        }.execute();
1286    }
1287
1288    private void setThemeColor(MaterialPalette palette) {
1289        // If the color is invalid, use the predefined default
1290        final int primaryColor = palette.mPrimaryColor;
1291        mScroller.setHeaderTintColor(primaryColor);
1292        mStatusBarColor = palette.mSecondaryColor;
1293        updateStatusBarColor();
1294
1295        mColorFilter =
1296                new PorterDuffColorFilter(primaryColor, PorterDuff.Mode.SRC_ATOP);
1297        mContactCard.setColorAndFilter(primaryColor, mColorFilter);
1298        mRecentCard.setColorAndFilter(primaryColor, mColorFilter);
1299        mAboutCard.setColorAndFilter(primaryColor, mColorFilter);
1300    }
1301
1302    private void updateStatusBarColor() {
1303        if (mScroller == null) {
1304            return;
1305        }
1306        final int desiredStatusBarColor;
1307        // Only use a custom status bar color if QuickContacts touches the top of the viewport.
1308        if (mScroller.getScrollNeededToBeFullScreen() <= 0) {
1309            desiredStatusBarColor = mStatusBarColor;
1310        } else {
1311            desiredStatusBarColor = Color.TRANSPARENT;
1312        }
1313        // Animate to the new color.
1314        if (desiredStatusBarColor != getWindow().getStatusBarColor()) {
1315            final ObjectAnimator animation = ObjectAnimator.ofInt(getWindow(), "statusBarColor",
1316                    getWindow().getStatusBarColor(), desiredStatusBarColor);
1317            animation.setDuration(ANIMATION_STATUS_BAR_COLOR_CHANGE_DURATION);
1318            animation.setEvaluator(new ArgbEvaluator());
1319            animation.start();
1320        }
1321    }
1322
1323    private int colorFromBitmap(Bitmap bitmap) {
1324        // Author of Palette recommends using 24 colors when analyzing profile photos.
1325        final int NUMBER_OF_PALETTE_COLORS = 24;
1326        final Palette palette = Palette.generate(bitmap, NUMBER_OF_PALETTE_COLORS);
1327        if (palette != null && palette.getVibrantSwatch() != null) {
1328            return palette.getVibrantSwatch().getRgb();
1329        }
1330        return 0;
1331    }
1332
1333    private List<Entry> contactInteractionsToEntries(List<ContactInteraction> interactions) {
1334        final List<Entry> entries = new ArrayList<>();
1335        for (ContactInteraction interaction : interactions) {
1336            entries.add(new Entry(/* id = */ -1,
1337                    interaction.getIcon(this),
1338                    interaction.getViewHeader(this),
1339                    interaction.getViewBody(this),
1340                    interaction.getBodyIcon(this),
1341                    interaction.getViewFooter(this),
1342                    interaction.getFooterIcon(this),
1343                    interaction.getIntent(),
1344                    /* alternateIcon = */ null,
1345                    /* alternateIntent = */ null,
1346                    /* alternateContentDescription = */ null,
1347                    /* shouldApplyColor = */ true,
1348                    /* isEditable = */ false));
1349        }
1350        return entries;
1351    }
1352
1353    private final LoaderCallbacks<Contact> mLoaderContactCallbacks =
1354            new LoaderCallbacks<Contact>() {
1355        @Override
1356        public void onLoaderReset(Loader<Contact> loader) {
1357            mContactData = null;
1358        }
1359
1360        @Override
1361        public void onLoadFinished(Loader<Contact> loader, Contact data) {
1362            Trace.beginSection("onLoadFinished()");
1363
1364            if (isFinishing()) {
1365                return;
1366            }
1367            if (data.isError()) {
1368                // This shouldn't ever happen, so throw an exception. The {@link ContactLoader}
1369                // should log the actual exception.
1370                throw new IllegalStateException("Failed to load contact", data.getException());
1371            }
1372            if (data.isNotFound()) {
1373                if (mHasAlreadyBeenOpened) {
1374                    finish();
1375                } else {
1376                    Log.i(TAG, "No contact found: " + ((ContactLoader)loader).getLookupUri());
1377                    Toast.makeText(QuickContactActivity.this, R.string.invalidContactMessage,
1378                            Toast.LENGTH_LONG).show();
1379                }
1380                return;
1381            }
1382
1383            bindContactData(data);
1384
1385            Trace.endSection();
1386        }
1387
1388        @Override
1389        public Loader<Contact> onCreateLoader(int id, Bundle args) {
1390            if (mLookupUri == null) {
1391                Log.wtf(TAG, "Lookup uri wasn't initialized. Loader was started too early");
1392            }
1393            // Load all contact data. We need loadGroupMetaData=true to determine whether the
1394            // contact is invisible. If it is, we need to display an "Add to Contacts" MenuItem.
1395            return new ContactLoader(getApplicationContext(), mLookupUri,
1396                    true /*loadGroupMetaData*/, false /*loadInvitableAccountTypes*/,
1397                    true /*postViewNotification*/, true /*computeFormattedPhoneNumber*/);
1398        }
1399    };
1400
1401    @Override
1402    public void onBackPressed() {
1403        if (mScroller != null) {
1404            if (!mIsExitAnimationInProgress) {
1405                mScroller.scrollOffBottom();
1406            }
1407        } else {
1408            super.onBackPressed();
1409        }
1410    }
1411
1412    @Override
1413    public void finish() {
1414        super.finish();
1415
1416        // override transitions to skip the standard window animations
1417        overridePendingTransition(0, 0);
1418    }
1419
1420    private final LoaderCallbacks<List<ContactInteraction>> mLoaderInteractionsCallbacks =
1421            new LoaderCallbacks<List<ContactInteraction>>() {
1422
1423        @Override
1424        public Loader<List<ContactInteraction>> onCreateLoader(int id, Bundle args) {
1425            Log.v(TAG, "onCreateLoader");
1426            Loader<List<ContactInteraction>> loader = null;
1427            switch (id) {
1428                case LOADER_SMS_ID:
1429                    Log.v(TAG, "LOADER_SMS_ID");
1430                    loader = new SmsInteractionsLoader(
1431                            QuickContactActivity.this,
1432                            args.getStringArray(KEY_LOADER_EXTRA_PHONES),
1433                            MAX_SMS_RETRIEVE);
1434                    break;
1435                case LOADER_CALENDAR_ID:
1436                    Log.v(TAG, "LOADER_CALENDAR_ID");
1437                    final String[] emailsArray = args.getStringArray(KEY_LOADER_EXTRA_EMAILS);
1438                    List<String> emailsList = null;
1439                    if (emailsArray != null) {
1440                        emailsList = Arrays.asList(args.getStringArray(KEY_LOADER_EXTRA_EMAILS));
1441                    }
1442                    loader = new CalendarInteractionsLoader(
1443                            QuickContactActivity.this,
1444                            emailsList,
1445                            MAX_FUTURE_CALENDAR_RETRIEVE,
1446                            MAX_PAST_CALENDAR_RETRIEVE,
1447                            FUTURE_MILLISECOND_TO_SEARCH_LOCAL_CALENDAR,
1448                            PAST_MILLISECOND_TO_SEARCH_LOCAL_CALENDAR);
1449                    break;
1450                case LOADER_CALL_LOG_ID:
1451                    Log.v(TAG, "LOADER_CALL_LOG_ID");
1452                    loader = new CallLogInteractionsLoader(
1453                            QuickContactActivity.this,
1454                            args.getStringArray(KEY_LOADER_EXTRA_PHONES),
1455                            MAX_CALL_LOG_RETRIEVE);
1456            }
1457            return loader;
1458        }
1459
1460        @Override
1461        public void onLoadFinished(Loader<List<ContactInteraction>> loader,
1462                List<ContactInteraction> data) {
1463            mRecentLoaderResults.put(loader.getId(), data);
1464
1465            if (isAllRecentDataLoaded()) {
1466                bindRecentData();
1467            }
1468        }
1469
1470        @Override
1471        public void onLoaderReset(Loader<List<ContactInteraction>> loader) {
1472            mRecentLoaderResults.remove(loader.getId());
1473        }
1474    };
1475
1476    private boolean isAllRecentDataLoaded() {
1477        return mRecentLoaderResults.size() == mRecentLoaderIds.length;
1478    }
1479
1480    private void bindRecentData() {
1481        final List<ContactInteraction> allInteractions = new ArrayList<>();
1482        for (List<ContactInteraction> loaderInteractions : mRecentLoaderResults.values()) {
1483            allInteractions.addAll(loaderInteractions);
1484        }
1485
1486        // Sort the interactions by most recent
1487        Collections.sort(allInteractions, new Comparator<ContactInteraction>() {
1488            @Override
1489            public int compare(ContactInteraction a, ContactInteraction b) {
1490                return a.getInteractionDate() >= b.getInteractionDate() ? -1 : 1;
1491            }
1492        });
1493
1494
1495        List<List<Entry>> interactionsWrapper = new ArrayList<>();
1496        interactionsWrapper.add(contactInteractionsToEntries(allInteractions));
1497        if (allInteractions.size() > 0) {
1498            mRecentCard.initialize(interactionsWrapper,
1499                    /* numInitialVisibleEntries = */ MIN_NUM_COLLAPSED_RECENT_ENTRIES_SHOWN,
1500                    /* isExpanded = */ false, mExpandingEntryCardViewListener);
1501            mRecentCard.setVisibility(View.VISIBLE);
1502        }
1503
1504        // About card is initialized along with the contact card, but since it appears after
1505        // the recent card in the UI, we hold off until making it visible until the recent card
1506        // is also ready to avoid stuttering.
1507        if (mAboutCard.shouldShow()) {
1508            mAboutCard.setVisibility(View.VISIBLE);
1509        } else {
1510            mAboutCard.setVisibility(View.GONE);
1511        }
1512    }
1513
1514    @Override
1515    protected void onStop() {
1516        super.onStop();
1517
1518        if (mEntriesAndActionsTask != null) {
1519            // Once the activity is stopped, we will no longer want to bind mEntriesAndActionsTask's
1520            // results on the UI thread. In some circumstances Activities are killed without
1521            // onStop() being called. This is not a problem, because in these circumstances
1522            // the entire process will be killed.
1523            mEntriesAndActionsTask.cancel(/* mayInterruptIfRunning = */ false);
1524        }
1525    }
1526
1527    /**
1528     * Returns true if it is possible to edit the current contact.
1529     */
1530    private boolean isContactEditable() {
1531        return mContactData != null && !mContactData.isDirectoryEntry();
1532    }
1533
1534    private Intent getEditContactIntent() {
1535        final Intent intent = new Intent(Intent.ACTION_EDIT, mLookupUri);
1536        mContactLoader.cacheResult();
1537        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
1538        return intent;
1539    }
1540
1541    private void editContact() {
1542        startActivityForResult(getEditContactIntent(), REQUEST_CODE_CONTACT_EDITOR_ACTIVITY);
1543    }
1544
1545    private void toggleStar(MenuItem starredMenuItem) {
1546        // Make sure there is a contact
1547        if (mLookupUri != null) {
1548            // Read the current starred value from the UI instead of using the last
1549            // loaded state. This allows rapid tapping without writing the same
1550            // value several times
1551            final boolean isStarred = starredMenuItem.isChecked();
1552
1553            // To improve responsiveness, swap out the picture (and tag) in the UI already
1554            ContactDetailDisplayUtils.configureStarredMenuItem(starredMenuItem,
1555                    mContactData.isDirectoryEntry(), mContactData.isUserProfile(),
1556                    !isStarred);
1557
1558            // Now perform the real save
1559            final Intent intent = ContactSaveService.createSetStarredIntent(
1560                    QuickContactActivity.this, mLookupUri, !isStarred);
1561            startService(intent);
1562
1563            final CharSequence accessibilityText = !isStarred
1564                    ? getResources().getText(R.string.description_action_menu_add_star)
1565                    : getResources().getText(R.string.description_action_menu_remove_star);
1566            // Accessibility actions need to have an associated view. We can't access the MenuItem's
1567            // underlying view, so put this accessibility action on the root view.
1568            mScroller.announceForAccessibility(accessibilityText);
1569        }
1570    }
1571
1572    /**
1573     * Calls into the contacts provider to get a pre-authorized version of the given URI.
1574     */
1575    private Uri getPreAuthorizedUri(Uri uri) {
1576        final Bundle uriBundle = new Bundle();
1577        uriBundle.putParcelable(ContactsContract.Authorization.KEY_URI_TO_AUTHORIZE, uri);
1578        final Bundle authResponse = getContentResolver().call(
1579                ContactsContract.AUTHORITY_URI,
1580                ContactsContract.Authorization.AUTHORIZATION_METHOD,
1581                null,
1582                uriBundle);
1583        if (authResponse != null) {
1584            return (Uri) authResponse.getParcelable(
1585                    ContactsContract.Authorization.KEY_AUTHORIZED_URI);
1586        } else {
1587            return uri;
1588        }
1589    }
1590
1591    private void shareContact() {
1592        final String lookupKey = mContactData.getLookupKey();
1593        Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
1594        if (mContactData.isUserProfile()) {
1595            // User is sharing the profile.  We don't want to force the receiver to have
1596            // the highly-privileged READ_PROFILE permission, so we need to request a
1597            // pre-authorized URI from the provider.
1598            shareUri = getPreAuthorizedUri(shareUri);
1599        }
1600
1601        final Intent intent = new Intent(Intent.ACTION_SEND);
1602        intent.setType(Contacts.CONTENT_VCARD_TYPE);
1603        intent.putExtra(Intent.EXTRA_STREAM, shareUri);
1604
1605        // Launch chooser to share contact via
1606        final CharSequence chooseTitle = getText(R.string.share_via);
1607        final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);
1608
1609        try {
1610            this.startActivity(chooseIntent);
1611        } catch (final ActivityNotFoundException ex) {
1612            Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
1613        }
1614    }
1615
1616    /**
1617     * Creates a launcher shortcut with the current contact.
1618     */
1619    private void createLauncherShortcutWithContact() {
1620        final ShortcutIntentBuilder builder = new ShortcutIntentBuilder(this,
1621                new OnShortcutIntentCreatedListener() {
1622
1623                    @Override
1624                    public void onShortcutIntentCreated(Uri uri, Intent shortcutIntent) {
1625                        // Broadcast the shortcutIntent to the launcher to create a
1626                        // shortcut to this contact
1627                        shortcutIntent.setAction(ACTION_INSTALL_SHORTCUT);
1628                        QuickContactActivity.this.sendBroadcast(shortcutIntent);
1629
1630                        // Send a toast to give feedback to the user that a shortcut to this
1631                        // contact was added to the launcher.
1632                        Toast.makeText(QuickContactActivity.this,
1633                                R.string.createContactShortcutSuccessful,
1634                                Toast.LENGTH_SHORT).show();
1635                    }
1636
1637                });
1638        builder.createContactShortcutIntent(mLookupUri);
1639    }
1640
1641    @Override
1642    public boolean onCreateOptionsMenu(Menu menu) {
1643        final MenuInflater inflater = getMenuInflater();
1644        inflater.inflate(R.menu.quickcontact, menu);
1645        return true;
1646    }
1647
1648    @Override
1649    public boolean onPrepareOptionsMenu(Menu menu) {
1650        if (mContactData != null) {
1651            final MenuItem starredMenuItem = menu.findItem(R.id.menu_star);
1652            ContactDetailDisplayUtils.configureStarredMenuItem(starredMenuItem,
1653                    mContactData.isDirectoryEntry(), mContactData.isUserProfile(),
1654                    mContactData.getStarred());
1655            // Configure edit MenuItem
1656            final MenuItem editMenuItem = menu.findItem(R.id.menu_edit);
1657            editMenuItem.setVisible(true);
1658            if (DirectoryContactUtil.isDirectoryContact(mContactData) || InvisibleContactUtil
1659                    .isInvisibleAndAddable(mContactData, this)) {
1660                editMenuItem.setIcon(R.drawable.ic_person_add_tinted_24dp);
1661                editMenuItem.setTitle(R.string.menu_add_contact);
1662            } else if (isContactEditable()) {
1663                editMenuItem.setIcon(R.drawable.ic_create_24dp);
1664                editMenuItem.setTitle(R.string.menu_editContact);
1665            } else {
1666                editMenuItem.setVisible(false);
1667            }
1668            return true;
1669        }
1670        return false;
1671    }
1672
1673    @Override
1674    public boolean onOptionsItemSelected(MenuItem item) {
1675        switch (item.getItemId()) {
1676            case R.id.menu_star:
1677                toggleStar(item);
1678                return true;
1679            case R.id.menu_edit:
1680                if (DirectoryContactUtil.isDirectoryContact(mContactData)) {
1681                    DirectoryContactUtil.addToMyContacts(mContactData, this, getFragmentManager(),
1682                            mSelectAccountFragmentListener);
1683                } else if (InvisibleContactUtil.isInvisibleAndAddable(mContactData, this)) {
1684                    InvisibleContactUtil.addToDefaultGroup(mContactData, this);
1685                } else if (isContactEditable()) {
1686                    editContact();
1687                }
1688                return true;
1689            case R.id.menu_share:
1690                shareContact();
1691                return true;
1692            case R.id.menu_create_contact_shortcut:
1693                createLauncherShortcutWithContact();
1694                return true;
1695            default:
1696                return super.onOptionsItemSelected(item);
1697        }
1698    }
1699}
1700