/* * Copyright (C) 2007 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; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.BroadcastReceiver; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract; import android.content.DialogInterface; import android.content.IContentService; import android.content.Intent; import android.content.IntentFilter; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.res.ColorStateList; import android.content.res.Resources; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Parcelable; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.Intents.UI; import android.provider.Contacts.People; import android.provider.Contacts.PeopleColumns; import android.provider.Contacts.Phones; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.ContactCounts; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Contacts.AggregationSuggestions; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.Intents.Insert; import android.provider.ContactsContract.ProviderStatus; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.provider.Settings; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.Html; import com.android.contacts.ui.widget.BladeView; import android.text.InputFilter; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.QuickContactBadge; import android.widget.SectionIndexer; import android.widget.TextView; import android.widget.Toast; import com.android.contacts.TextHighlightingAnimation.TextWithHighlighting; import com.android.contacts.model.ContactsSource; import com.android.contacts.model.Sources; import com.android.contacts.ui.ContactsPreferences; import com.android.contacts.ui.ContactsPreferencesActivity; import com.android.contacts.ui.EditContactActivity; import com.android.contacts.ui.ContactsPreferencesActivity.Prefs; import com.android.contacts.ui.SimEditContactActivity; import com.android.contacts.ui.SimUtils; import com.android.contacts.util.AccountSelectionUtil; import com.android.contacts.util.CommonUtil; import com.android.contacts.util.Constants; import com.android.internal.telephony.AdnRecord; import com.android.internal.telephony.EncodeException; import com.android.internal.telephony.GsmAlphabet; import com.android.internal.telephony.IIccPhoneBook; import com.android.internal.telephony.IccConstants; //added for dual sim import com.android.contacts.util.Config; import android.content.res.Resources.NotFoundException; import android.os.Message; import java.util.HashSet; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.android.internal.telephony.PhoneFactory; import android.widget.AlphabetIndexer; import android.widget.ResourceCursorAdapter; import java.lang.ref.SoftReference; /*TODO(emillar) I commented most of the code that deals with modes and filtering. It should be * brought back in as we add back that functionality. */ /** * Displays a list of contacts. Usually is embedded into the ContactsActivity. */ @SuppressWarnings("deprecation") public class ContactsListActivity extends ListActivity implements View.OnCreateContextMenuListener, View.OnClickListener, View.OnKeyListener, TextWatcher, TextView.OnEditorActionListener, OnFocusChangeListener, OnTouchListener { public static class JoinContactActivity extends ContactsListActivity { } public static class ContactsSearchActivity extends ContactsListActivity { } private boolean mIsFirstQuery; private int mContactsGroupNameId; private String mContactsGroupName; private String mContactsGroupRingtone; private boolean hasStarredContacts = false; private boolean hasFreQuentContacts = false; private boolean isEnableDeleteMenu = false; private static final String TAG = "ContactsListActivity"; private static final boolean ENABLE_ACTION_ICON_OVERLAYS = true; private static final String LIST_STATE_KEY = "liststate"; private static final String SHORTCUT_ACTION_KEY = "shortcutAction"; static final int MENU_ITEM_VIEW_CONTACT = 1; static final int MENU_ITEM_CALL = 2; static final int MENU_ITEM_EDIT_BEFORE_CALL = 3; static final int MENU_ITEM_SEND_SMS = 4; static final int MENU_ITEM_SEND_IM = 5; static final int MENU_ITEM_EDIT = 6; static final int MENU_ITEM_DELETE = 7; static final int MENU_ITEM_TOGGLE_STAR = 8; static final int MENU_ITEM_IMPORT = 9; static final int MENU_ITEM_EXPORT = 10; static final int MENU_ITEM_VIDEOCALL = 11; static final int MENU_ITEM_ADD_TO_FIRE_WALL = 12; static final int MENU_ITEM_SHARE_BY_SMS = 13;/* fixed CR<NEWMS00120798> by luning at 2011.11.08*/ static final int MENU_ITEM_SHARE_BY_MMS = 14;/* fixed CR<NEWMS00120798> by luning at 2011.11.08*/ static final int MENU_ITEM_ADD_BLACK = 15; static final int MENU_ITEM_SHARE_BY_BLUETOOTH = 16; static final int MENU_ITEM_REMOVE_FREQUENT = 17; static final int MENU_ITEM_SHARE_BY_EMAIL = 20; //added for dual sim static final int MENU_ITEM_EXPORT_TO_SIM1 = 18; static final int MENU_ITEM_EXPORT_TO_SIM2 = 19; private static final int SUBACTIVITY_NEW_CONTACT = 1; private static final int SUBACTIVITY_VIEW_CONTACT = 2; private static final int SUBACTIVITY_DISPLAY_GROUP = 3; private static final int SUBACTIVITY_SEARCH = 4; private static final int SUBACTIVITY_FILTER = 5; private static final int SUBACTIVITY_EDIT_CONTACT = 6; public static final int REQUEST_CODE_FOR_GROUP_ALL = 100; private static final int DLG_ADD_BLACK = 1000; private static final int GROUP_NAME_STUDENT = 0; private static final int GROUP_NAME_FRIEND = 1; private static final int GROUP_NAME_FAMILY = 2; private static final int GROUP_NAME_COLLEAGUE = 3; /** * bin.lai */ static final int MENU_ITEM_DIVIDED_GROUP = 44444; static final int MENU_ITEM_REMOVE_CONTACTS_FROM_GROUP = 55555; private static final int TEXT_HIGHLIGHTING_ANIMATION_DURATION = 350; /** * The action for the join contact activity. * <p> * Input: extra field {@link #EXTRA_AGGREGATE_ID} is the aggregate ID. * * TODO: move to {@link ContactsContract}. */ public static final String JOIN_AGGREGATE = "com.android.contacts.action.JOIN_AGGREGATE"; /** * Used with {@link #JOIN_AGGREGATE} to give it the target for aggregation. * <p> * Type: LONG */ public static final String EXTRA_AGGREGATE_ID = "com.android.contacts.action.AGGREGATE_ID"; /** * Used with {@link #JOIN_AGGREGATE} to give it the name of the aggregation target. * <p> * Type: STRING */ @Deprecated public static final String EXTRA_AGGREGATE_NAME = "com.android.contacts.action.AGGREGATE_NAME"; public static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final Uri CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS = buildSectionIndexerUri(Contacts.CONTENT_URI); public enum Action { VOICECALL, VIDEOCALL, SENDSMS; } /** Mask for picker mode */ static final int MODE_MASK_PICKER = 0x80000000; /** Mask for no presence mode */ static final int MODE_MASK_NO_PRESENCE = 0x40000000; /** Mask for enabling list filtering */ static final int MODE_MASK_NO_FILTER = 0x20000000; /** Mask for having a "create new contact" header in the list */ static final int MODE_MASK_CREATE_NEW = 0x10000000; /** Mask for showing photos in the list */ static final int MODE_MASK_SHOW_PHOTOS = 0x08000000; /** Mask for hiding additional information e.g. primary phone number in the list */ static final int MODE_MASK_NO_DATA = 0x04000000; /** Mask for showing a call button in the list */ static final int MODE_MASK_SHOW_CALL_BUTTON = 0x02000000; /** Mask to disable quickcontact (images will show as normal images) */ static final int MODE_MASK_DISABLE_QUIKCCONTACT = 0x01000000; /** Mask to show the total number of contacts at the top */ static final int MODE_MASK_SHOW_NUMBER_OF_CONTACTS = 0x00800000; /** * bin.lai */ static final Uri DIVIDED_GROUP_URI=Uri.parse("content://"+ContactsContract.AUTHORITY+"/divided_group"); static final Uri STARRED_FREQUENT_URI = Uri.parse("content://"+ContactsContract.AUTHORITY+"/contacts"); /** Unknown mode */ static final int MODE_UNKNOWN = 0; /** Default mode */ static final int MODE_DEFAULT = 4 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Custom mode */ static final int MODE_CUSTOM = 8; /** Show all starred contacts */ static final int MODE_STARRED = 20 | MODE_MASK_SHOW_PHOTOS; /** Show frequently contacted contacts */ static final int MODE_FREQUENT = 30 | MODE_MASK_SHOW_PHOTOS; /** Show starred and the frequent */ static final int MODE_STREQUENT = 35 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_CALL_BUTTON; /** Show all contacts and pick them when clicking */ static final int MODE_PICK_CONTACT = 40 | MODE_MASK_PICKER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts as well as the option to create a new one */ static final int MODE_PICK_OR_CREATE_CONTACT = 42 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PERSON = 43 | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider as well as the option to create a new one */ static final int MODE_LEGACY_PICK_OR_CREATE_PERSON = 44 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts and pick them when clicking, and allow creating a new contact */ static final int MODE_INSERT_OR_EDIT_CONTACT = 45 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all phone numbers and pick them when clicking */ static final int MODE_PICK_PHONE = 50 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE; /** Show all phone numbers through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PHONE = 51 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_PICK_POSTAL = 55 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_LEGACY_PICK_POSTAL = 56 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; static final int MODE_GROUP = 57 | MODE_MASK_SHOW_PHOTOS; /** Run a search query */ static final int MODE_QUERY = 60 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to VIEW */ static final int MODE_QUERY_PICK_TO_VIEW = 65 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Show join suggestions followed by an A-Z list */ static final int MODE_JOIN_CONTACT = 70 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_DATA | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Run a search query in a PICK mode */ static final int MODE_QUERY_PICK = 75 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in a PICK_PHONE mode */ static final int MODE_QUERY_PICK_PHONE = 80 | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to EDIT */ static final int MODE_QUERY_PICK_TO_EDIT = 85 | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** * An action used to do perform search while in a contact picker. It is initiated * by the ContactListActivity itself. */ private static final String ACTION_SEARCH_INTERNAL = "com.android.contacts.INTERNAL_SEARCH"; /** Maximum number of suggestions shown for joining aggregates */ static final int MAX_SUGGESTIONS = 4; static final String NAME_COLUMN = Contacts.DISPLAY_NAME; //static final String SORT_STRING = People.SORT_STRING; static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 RawContacts.SIM_INDEX, // 11 //added for dual sim RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, }; static final String[] CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 // email lookup doesn't included HAS_PHONE_NUMBER in projection //added for dual sim RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, }; static final String[] CONTACTS_SUMMARY_FILTER_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 RawContacts.SIM_INDEX, // 11 SearchSnippetColumns.SNIPPET_MIMETYPE, // 12 SearchSnippetColumns.SNIPPET_DATA1, // 13 SearchSnippetColumns.SNIPPET_DATA4, // 14 //added for dual sim RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, }; static final String[] LEGACY_PEOPLE_PROJECTION = new String[] { People._ID, // 0 People.DISPLAY_NAME, // 1 People.DISPLAY_NAME, // 2 People.DISPLAY_NAME, // 3 People.STARRED, // 4 PeopleColumns.TIMES_CONTACTED, // 5 People.PRESENCE_STATUS, // 6 //added for dual sim RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, }; static final int SUMMARY_ID_COLUMN_INDEX = 0; static final int SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX = 1; static final int SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX = 2; static final int SUMMARY_SORT_KEY_PRIMARY_COLUMN_INDEX = 3; static final int SUMMARY_STARRED_COLUMN_INDEX = 4; static final int SUMMARY_TIMES_CONTACTED_COLUMN_INDEX = 5; static final int SUMMARY_PRESENCE_STATUS_COLUMN_INDEX = 6; static final int SUMMARY_PHOTO_ID_COLUMN_INDEX = 7; static final int SUMMARY_LOOKUP_KEY_COLUMN_INDEX = 8; static final int SUMMARY_PHONETIC_NAME_COLUMN_INDEX = 9; static final int SUMMARY_HAS_PHONE_COLUMN_INDEX = 10; static final int SUMMARY_SIM_COLUMN_INDEX = 11; static final int SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX = 12; static final int SUMMARY_SNIPPET_DATA1_COLUMN_INDEX = 13; static final int SUMMARY_SNIPPET_DATA4_COLUMN_INDEX = 14; //added for dual sim static final int SUMMARY_ACCOUNT_NAME = 15; static final String[] PHONES_PROJECTION = new String[] { Phone._ID, //0 Phone.TYPE, //1 Phone.LABEL, //2 Phone.NUMBER, //3 Phone.DISPLAY_NAME, // 4 Phone.CONTACT_ID, // 5 //added for dual sim RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, }; static final String[] LEGACY_PHONES_PROJECTION = new String[] { Phones._ID, //0 Phones.TYPE, //1 Phones.LABEL, //2 Phones.NUMBER, //3 People.DISPLAY_NAME, // 4 }; static final int PHONE_ID_COLUMN_INDEX = 0; static final int PHONE_TYPE_COLUMN_INDEX = 1; static final int PHONE_LABEL_COLUMN_INDEX = 2; static final int PHONE_NUMBER_COLUMN_INDEX = 3; static final int PHONE_DISPLAY_NAME_COLUMN_INDEX = 4; static final int PHONE_CONTACT_ID_COLUMN_INDEX = 5; static final String[] POSTALS_PROJECTION = new String[] { StructuredPostal._ID, //0 StructuredPostal.TYPE, //1 StructuredPostal.LABEL, //2 StructuredPostal.DATA, //3 StructuredPostal.DISPLAY_NAME, // 4 }; static final String[] LEGACY_POSTALS_PROJECTION = new String[] { ContactMethods._ID, //0 ContactMethods.TYPE, //1 ContactMethods.LABEL, //2 ContactMethods.DATA, //3 People.DISPLAY_NAME, // 4 }; static final String[] RAW_CONTACTS_PROJECTION = new String[] { RawContacts._ID, //0 RawContacts.CONTACT_ID, //1 RawContacts.ACCOUNT_TYPE, //2 //added for dual sim RawContacts.ACCOUNT_NAME, }; static final int POSTAL_ID_COLUMN_INDEX = 0; static final int POSTAL_TYPE_COLUMN_INDEX = 1; static final int POSTAL_LABEL_COLUMN_INDEX = 2; static final int POSTAL_ADDRESS_COLUMN_INDEX = 3; static final int POSTAL_DISPLAY_NAME_COLUMN_INDEX = 4; private static final int QUERY_TOKEN = 42; static final String KEY_PICKER_MODE = "picker_mode"; private ContactItemListAdapter mAdapter; int mMode = MODE_DEFAULT; private static boolean mQueryComplete=false; private QueryHandler mQueryHandler; private boolean mJustCreated; private boolean mSyncEnabled; Uri mSelectedContactUri; // private boolean mDisplayAll; private boolean mDisplayOnlyPhones; private Uri mGroupUri; private long mQueryAggregateId; private ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>(); private int mWritableSourcesCnt; private int mReadOnlySourcesCnt; /** * Used to keep track of the scroll state of the list. */ private Parcelable mListState = null; private boolean mListHasFocus; private String mShortcutAction; private int mScrollState; /** * Internal query type when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. */ private int mQueryMode = QUERY_MODE_NONE; private static final int QUERY_MODE_NONE = -1; private static final int QUERY_MODE_MAILTO = 1; private static final int QUERY_MODE_TEL = 2; private int mProviderStatus = ProviderStatus.STATUS_NORMAL; private boolean mSearchMode; private boolean mSearchResultsMode; private boolean mShowNumberOfContacts; private boolean mShowSearchSnippets; private boolean mSearchInitiated; private String mInitialFilter; private static final int GROUP_ALL = 0; private static final int GROUP_PHONE = 1; private static final int GROUP_SIM = 2; //added for dual sim private static final int GROUP_SIM1 = 4; private static final int GROUP_SIM2 = 5; private static final int MODE_DELETE = 1; private static final int MODE_EXPORT = 2; private static final int MODE_IMPORT = 3; private static final int MODE_ADD_CONTACTS_GROUP = 9; private static final int MODE_REMOVE_COLLECTION_CONTACTS = 10; private static final int MODE_REMOVE_FREQUENT_CONTACTS = 11; private static final int MODE_SDCARD_EXPORT = 6; private static final int MODE_BT_SHARE = 7; private static final int MODE_VIEW = 0; private static final int MODE_EDIT = 1; private static final int MODE_INSERT = 2; private int mContactsGroup=GROUP_ALL; private int mPreContactsGroup=GROUP_ALL; private final String PROPERTY_ICC_OPERATOR_NUMERIC = "gsm.sim.operator.numeric"; private final String PROPERTY_RO_DEVICE_SUPPORT_BT = "ro.device.support.bt"; /** * Data to use when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. Usually * provided by scheme-specific part of incoming {@link Intent#getData()}. */ private String mQueryData; private static final String CLAUSE_ONLY_VISIBLE = Contacts.IN_VISIBLE_GROUP + "=1"; private static final String CLAUSE_ONLY_PHONES = Contacts.HAS_PHONE_NUMBER + "=1"; private static String ADD_BLACK_NUMBERS = "addBlackNumbers"; /** * In the {@link #MODE_JOIN_CONTACT} determines whether we display a list item with the label * "Show all contacts" or actually show all contacts */ private boolean mJoinModeShowAllContacts; /** * The ID of the special item described above. */ private static final long JOIN_MODE_SHOW_ALL_CONTACTS_ID = -2; // Uri matcher for contact id private static final int CONTACTS_ID = 1001; private static final UriMatcher sContactsIdMatcher; private ContactPhotoLoader mPhotoLoader; private Context mContext; private static Bundle mBundle; private boolean isEmail = false; final String[] sLookupProjection = new String[] { Contacts.LOOKUP_KEY }; static { sContactsIdMatcher = new UriMatcher(UriMatcher.NO_MATCH); sContactsIdMatcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID); } private boolean isActivityTop = false; private boolean isDataChange = false; private class DeleteClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { if (mSelectedContactUri != null) { int rawNumber = getContentResolver().delete(mSelectedContactUri, null, null); Log.d(TAG, "rawNumber = " + rawNumber); if(rawNumber >= 0) { Toast.makeText(ContactsListActivity.this, R.string.delete_phone_success, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ContactsListActivity.this, R.string.delete_phone_fail, Toast.LENGTH_SHORT).show(); } } } } private class DeleteSimClickListener implements DialogInterface.OnClickListener { String mSimIndex; String mAccountName; public DeleteSimClickListener(String simIndex, String accountName) { mSimIndex=simIndex; mAccountName=accountName; } public void onClick(DialogInterface dialog, int which) { if(getContentResolver().delete(getSimUri(), "sim_index=? and account_name=?", new String[]{mSimIndex, mAccountName}) > 0){ Toast.makeText(ContactsListActivity.this, R.string.delete_sim_success, Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(ContactsListActivity.this, R.string.delete_sim_fail, Toast.LENGTH_SHORT).show(); } } } /** * A {@link TextHighlightingAnimation} that redraws just the contact display name in a * list item. */ private static class NameHighlightingAnimation extends TextHighlightingAnimation { private final ListView mListView; private NameHighlightingAnimation(ListView listView, int duration) { super(duration); this.mListView = listView; } /** * Redraws all visible items of the list corresponding to contacts */ @Override protected void invalidate() { int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i++) { View itemView = mListView.getChildAt(i); if (itemView instanceof ContactListItemView) { final ContactListItemView view = (ContactListItemView)itemView; view.getNameTextView().invalidate(); } } } @Override protected void onAnimationStarted() { mListView.setScrollingCacheEnabled(false); } @Override protected void onAnimationEnded() { mListView.setScrollingCacheEnabled(true); } } // The size of a home screen shortcut icon. private int mIconSize; private ContactsPreferences mContactsPrefs; private int mDisplayOrder; private int mSortOrder; private boolean mHighlightWhenScrolling; private TextHighlightingAnimation mHighlightingAnimation; private SearchEditText mSearchEditText; /** * An approximation of the background color of the pinned header. This color * is used when the pinned header is being pushed up. At that point the header * "fades away". Rather than computing a faded bitmap based on the 9-patch * normally used for the background, we will use a solid color, which will * provide better performance and reduced complexity. */ private int mPinnedHeaderBackgroundColor; private ContentObserver mProviderStatusObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { checkProviderState(true); } }; protected Uri getSimUri() { return Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "sim_contacts"); } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Log.v(TAG, "onCreate"); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); if (null != this.getParent()) { mContext = this.getParent(); } else { mContext = this; } // Resolve the intent final Intent intent = getIntent(); isEmail = intent.hasExtra(Insert.EMAIL); mContactsGroupNameId = intent.getIntExtra("mContactsGroupNameId", -1); mContactsGroupName = intent.getStringExtra("mContactsGroupName"); mContactsGroupRingtone = intent.getStringExtra("mContactsGroupRingtone"); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (mContactsGroupNameId > -1) { title = getString(R.string.group_manager); } if (title != null) { setTitle(title); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ContactsListActivity.this); mContactsGroup=prefs.getInt("ContactsGroup",GROUP_ALL); String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; mShowSearchSnippets = false; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; mShowSearchSnippets = false; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mContactsGroup=GROUP_PHONE; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; mBundle = intent.getExtras(); } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); Cursor simCursor = getSimCursor(contactId); if(simCursor!=null){ startSimContactActivity(simCursor, MODE_VIEW); simCursor.close(); //modify by dory.zheng for NEWMS00136979 finish(); return; } final Cursor cursor = queryPhoneNumbers(contactId, null); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; // registerRefreshListViewReceiver(); } private Cursor getSimCursor(long contactId){ Uri uri = Contacts.CONTENT_URI; uri = uri.buildUpon().appendPath(Long.toString(contactId)).build(); Cursor cursor=getContentResolver().query(uri, CONTACTS_SUMMARY_PROJECTION, null, null, null); if (cursor != null && cursor.getCount() == 1) { cursor.moveToFirst(); int simIndex=cursor.getInt(SUMMARY_SIM_COLUMN_INDEX); if(simIndex!=0){ return cursor; } } cursor.close(); return null; } private String getSimContactSelection() { String selection=Contacts.IN_VISIBLE_GROUP + "=1"; return selection; } private int getSimContactsCount(){ int count = 0; Cursor cursor=getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, "sim_index<>0 AND "+getSimContactSelection(), null, getSortOrder(null)); if(cursor != null) { count = cursor.getCount(); cursor.close(); } Log.i(TAG, "getSimContactsCount " + count); return count; } //added for dual sim private int getSimContactsCount(int phoneId){ int count = 0; String accountName = null; if(phoneId==0){ accountName = Account.SIM1_ACCOUNT_NAME; } else{ accountName = Account.SIM2_ACCOUNT_NAME; } Cursor cursor=getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, "sim_index<>0 AND account_name='"+accountName+"' AND "+getSimContactSelection(), null, getSortOrder(null)); if(cursor != null) { count = cursor.getCount(); cursor.close(); } Log.i(TAG, "getSimContactsCount:" + count + ", phoneId:"+phoneId); return count; } private int getPhoneContactsCount(){ int count = 0; Cursor cursor=getContentResolver().query(CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS, CONTACTS_SUMMARY_PROJECTION, "sim_index=0", null, null); if(cursor != null){ count = cursor.getCount(); cursor.close(); } Log.i(TAG, "getPhoneContactsCount " + count); return count; } // private BroadcastReceiver mRefreshListViewReceiver; // // protected boolean airPlaneMode = false; // // private void registerRefreshListViewReceiver(){ // if(mRefreshListViewReceiver == null){ // mRefreshListViewReceiver = new BroadcastReceiver(){ // @Override // public void onReceive(Context context, Intent intent) { // // TODO Auto-generated method stub // String action = intent.getAction(); // if(action.equals(SyncSimContactsService.BROADCAST_ACTION_REFRESH)){ // Log.d(TAG, " BROADCAST_ACTION_REFRESH "); // ((ContactItemListAdapter)getListView().getAdapter()).notifyDataSetChanged(); // setEmptyText(); // // startQuery(); // }else if(action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){ // if(intent.getBooleanExtra("state", false)){ // Log.d(TAG, "get ACTION_AIRPLANE_MODE_CHANGED and state = true"); // airPlaneMode = true; // startQuery(); // ((ContactItemListAdapter)getListView().getAdapter()).notifyDataSetChanged(); // setEmptyText(); // }else{ // Log.d(TAG, "get ACTION_AIRPLANE_MODE_CHANGED and state = false"); // airPlaneMode = false; // } // } // } // }; // IntentFilter filter = new IntentFilter(); // filter.addAction(SyncSimContactsService.BROADCAST_ACTION_REFRESH); // filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); // registerReceiver(mRefreshListViewReceiver, filter); // } // } // // private void unregisterRefreshListViewReceiver(){ // if(mRefreshListViewReceiver != null){ // unregisterReceiver(mRefreshListViewReceiver); // mRefreshListViewReceiver = null; // } // } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void registerProviderStatusObserver() { getContentResolver().registerContentObserver(ProviderStatus.CONTENT_URI, false, mProviderStatusObserver); } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void unregisterProviderStatusObserver() { getContentResolver().unregisterContentObserver(mProviderStatusObserver); } private void setupListView() { final ListView list = getListView(); final LayoutInflater inflater = getLayoutInflater(); mHighlightingAnimation = new NameHighlightingAnimation(list, TEXT_HIGHLIGHTING_ANIMATION_DURATION); // Tell list view to not show dividers. We'll do it ourself so that we can *not* show // them when an A-Z headers is visible. list.setDividerHeight(0); list.setOnCreateContextMenuListener(this); //去除拖动时的黑块 list.setCacheColorHint(Color.TRANSPARENT); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); if (list instanceof PinnedHeaderListView && mAdapter.getDisplaySectionHeadersEnabled()) { mPinnedHeaderBackgroundColor = getResources().getColor(R.color.pinned_header_background); PinnedHeaderListView pinnedHeaderList = (PinnedHeaderListView)list; View pinnedHeader = inflater.inflate(R.layout.list_section, list, false); pinnedHeaderList.setPinnedHeaderView(pinnedHeader); } list.setOnScrollListener(mAdapter); list.setOnKeyListener(this); list.setOnFocusChangeListener(this); list.setOnTouchListener(this); configureBladeView(list); // We manually save/restore the listview state list.setSaveEnabled(false); } /** * Configures search UI. */ private void setupSearchView() { mSearchEditText = (SearchEditText)findViewById(R.id.search_src_text); mSearchEditText.setFilters(new InputFilter[]{ new InputFilter.LengthFilter( 255 )}); mSearchEditText.addTextChangedListener(this); mSearchEditText.setOnEditorActionListener(this); mSearchEditText.setText(mInitialFilter); } private String getContactDisplayName(long contactId) { String contactName = null; Cursor c = getContentResolver().query( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), new String[] {Contacts.DISPLAY_NAME}, null, null, null); try { if (c != null && c.moveToFirst()) { contactName = c.getString(0); } } finally { if (c != null) { c.close(); } } if (contactName == null) { contactName = ""; } return contactName; } private int getSummaryDisplayNameColumnIndex() { if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { return SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } else { return SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } } /** {@inheritDoc} */ public void onClick(View v) { int id = v.getId(); switch (id) { // TODO a better way of identifying the button case android.R.id.button1: { final int position = (Integer)v.getTag(); Cursor c = mAdapter.getCursor(); if (c != null) { c.moveToPosition(position); callContact(c); } break; } } } private boolean isSimInitializing(){ SharedPreferences prefState = getSharedPreferences(SyncSimContactsService.PREFS_SIM_FILE, MODE_PRIVATE); String state = prefState.getString(SyncSimContactsService.PREFS_SIM_KEY, SyncSimContactsService.PREFS_SIM_STATE_IDLE); boolean importing = state.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTING); if(Config.isMSMS){ String state0 = prefState.getString(SyncSimContactsService.PREFS_SIM_KEY0, SyncSimContactsService.PREFS_SIM_STATE_IDLE); String state1 = prefState.getString(SyncSimContactsService.PREFS_SIM_KEY1, SyncSimContactsService.PREFS_SIM_STATE_IDLE); importing = (state0.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTING) || state1.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTING)); } Log.d(TAG, "importing is " + importing + " state = " +state); return importing; //(importing || !booted || !haveImported); } //added for dual sim private boolean isSimInitializing(int phoneId){ //jun need to do! SharedPreferences prefState = getSharedPreferences(SyncSimContactsService.PREFS_SIM_FILE, MODE_PRIVATE); String state = prefState.getString(SyncSimContactsService.PREFS_SIM_KEY, SyncSimContactsService.PREFS_SIM_STATE_IDLE); boolean importing = state.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTING); Log.d(TAG, "importing is " + importing); return importing; } private void setEmptyText() { Log.v(TAG, "mMode = " + mMode); TextView empty = (TextView) findViewById(R.id.emptyText); Log.v(TAG, "empty = " + empty); if(empty == null){ }else{ int gravity = Gravity.NO_GRAVITY; if (mMode == MODE_JOIN_CONTACT||getListAdapter().getCount()!=0) { //CR243592 Modify Start // if(empty != null) { empty.setText(null); // } //CR243592 Modify End return; }else if(mMode==MODE_DEFAULT){ if (mDisplayOnlyPhones && mContactsGroupNameId < 0) { empty.setText(getText(R.string.noContactsWithPhoneNumbers)); gravity = Gravity.CENTER; }else if(mContactsGroup==GROUP_SIM){ if(simCardReady(true) && isSimInitializing()){ empty.setText(getText(R.string.sim_is_initializing)); }else{ empty.setText(getText(R.string.noContactsWithSimNumbers)); } gravity = Gravity.CENTER; }else if(mContactsGroup==GROUP_SIM1){ if(CommonUtil.isSimCardReady(0, true, mContext) && isSimInitializing(0)){ empty.setText(getText(R.string.sim_is_initializing1)); }else{ empty.setText(getText(R.string.noContactsWithSimNumbers1)); } gravity = Gravity.CENTER; }else if(mContactsGroup==GROUP_SIM2){ if( CommonUtil.isSimCardReady(1, true, mContext) && isSimInitializing(1)){ empty.setText(getText(R.string.sim_is_initializing2)); }else{ empty.setText(getText(R.string.noContactsWithSimNumbers2)); } gravity = Gravity.CENTER; }else { if(Config.isMSMS){ if(( CommonUtil.isSimCardReady(0, true, mContext) || CommonUtil.isSimCardReady(1, true, mContext) ) && isSimInitializing()){ Log.v(TAG, "simCardReady(0) || simCardReady(1) && isSimInitializing()"); empty.setText(getText(R.string.sim_is_initializing)); gravity = Gravity.CENTER; }else{ if (mContactsGroupNameId > -1) { // contacts group don't have contacts. String name = getText(R.string.noContacts_in_group).toString(); empty.setText(name); } else { empty.setText(getText(R.string.noContactsHelpText)); } } } else{ if(simCardReady(true) && isSimInitializing()){ Log.v(TAG, "simCardReady() && isSimInitializing()"); empty.setText(getText(R.string.sim_is_initializing)); gravity = Gravity.CENTER; }else{ if (mContactsGroupNameId > -1) { // contacts group don't have contacts. String name = getText(R.string.noContacts_in_group).toString(); empty.setText(name); } else { empty.setText(getText(R.string.noContactsHelpText)); } } } } }else if (mMode == MODE_STREQUENT || mMode == MODE_STARRED) { empty.setText(getText(R.string.noFavoritesHelpText)); } else if (mMode == MODE_QUERY) { empty.setText(getText(R.string.noMatchingContacts)); } empty.setGravity(gravity); } } private boolean simCardReady(boolean justCheckSimStateReady){ TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); int simState = tm.getSimState(); int adnCacheState = tm.getAdnCachestate(); Log.v(TAG, "getSimState = " + simState); Log.v(TAG, "adnCacheState = " + adnCacheState); if(TelephonyManager.SIM_STATE_READY == simState){ Log.v(TAG, "sim ready"); if (justCheckSimStateReady) { return true; } if (CommonUtil.isFdnEnable(mContext)) { Log.d(TAG, "FDN has enable"); simCardReadyToast(false); return false; } if (adnCacheState == Constants.ADNCACHE_STATE_NOT_READY) { Log.v(TAG, "adn cache not ready"); simCardReadyToast(false); return false; } return true; }else{ simCardReadyToast(true); return false; } } private void simCardReadyToast(boolean justCheckSimStateReady) { String message = null; TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (!(TelephonyManager.SIM_STATE_READY == tm.getSimState())) { message = getString(R.string.sim_no_ready); } else if (justCheckSimStateReady) { // just check sim state is ready or not, so return. return; } else if (CommonUtil.isFdnEnable(mContext)) { message = getString(R.string.fdn_enable_nosetting); } else if (tm.getAdnCachestate() == Constants.ADNCACHE_STATE_NOT_READY) { message = getString(R.string.initializing_sim_contacts); } if (null != message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } } // TODO support double sim. private boolean isFdnEnable(){ if(((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getIccFdnEnabled()){ Log.v(TAG, "Fdn Enable"); return true; }else{ return false; } } //added for dual sim private boolean isFdnEnableDualSim(int phoneId){ final TelephonyManager telManager = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, phoneId)); if(telManager.getIccFdnEnabled()){ Log.d(TAG, "phone" +phoneId + " fdn is enabled"); simCardFdnEableToast(phoneId); return true; } return false; } private boolean simCardReady(int phoneId){ final TelephonyManager telManager = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, phoneId)); int adnCacheState = telManager.getAdnCachestate(); boolean isFdnEnabled = telManager.getIccFdnEnabled(); if(isFdnEnabled){ Log.d(TAG, "Fdn is enabled in phone " + phoneId); simCardFdnEableToast(phoneId); return false; } if(TelephonyManager.SIM_STATE_READY == telManager.getSimState()){ Log.v(TAG, "sim ready:"+phoneId); if (adnCacheState == Constants.ADNCACHE_STATE_NOT_READY) { Log.v(TAG, "adn cache not ready"); simCardReadyToast(phoneId); return false; } return true; }else{ return false; } } //added for dual sim private void simCardFdnEableToast(int phoneId){ Toast.makeText(this, phoneId==0?getString(R.string.sim1_fdn_enable):getString(R.string.sim2_fdn_enable), Toast.LENGTH_SHORT).show(); } private void simCardReadyToast(int phoneId){ //if(!simCardReady(phoneId)){ Toast.makeText(this, phoneId==0?getString(R.string.sim1_no_ready):getString(R.string.sim2_no_ready), Toast.LENGTH_SHORT).show(); // } } private boolean isSyncActive() { Account[] accounts = AccountManager.get(this).getAccounts(); if (accounts != null && accounts.length > 0) { IContentService contentService = ContentResolver.getContentService(); for (Account account : accounts) { try { if (contentService.isSyncActive(account, ContactsContract.AUTHORITY)) { return true; } } catch (RemoteException e) { Log.e(TAG, "Could not get the sync status"); } } } return false; } private void buildUserGroupUri(String group) { mGroupUri = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, group); } /** * Sets the mode when the request is for "default" */ private void setDefaultMode() { // Load the preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mDisplayOnlyPhones = prefs.getBoolean(Prefs.DISPLAY_ONLY_PHONES, Prefs.DISPLAY_ONLY_PHONES_DEFAULT); } @Override protected void onDestroy() { super.onDestroy(); mPhotoLoader.stop(); // unregisterRefreshListViewReceiver(); if(mAdapter != null) { mAdapter.setSuggestionsCursor(null); mAdapter.changeCursor(null); } } @Override protected void onStart() { super.onStart(); mContactsPrefs.registerChangeListener(mPreferencesChangeListener); } @Override protected void onPause() { super.onPause(); isActivityTop = false; unregisterProviderStatusObserver(); } @Override protected void onResume() { super.onResume(); Log.v(TAG, "onResume"); //mContactsGroupNameId = -1; registerProviderStatusObserver(); mPhotoLoader.resume(); isActivityTop = true; Activity parent = getParent(); // Do this before setting the filter. The filter thread relies // on some state that is initialized in setDefaultMode if (mMode == MODE_DEFAULT) { // If we're in default mode we need to possibly reset the mode due to a change // in the preferences activity while we weren't running setDefaultMode(); } // See if we were invoked with a filter if (mSearchMode) { mSearchEditText.requestFocus(); } if (!mSearchMode && !checkProviderState(mJustCreated)) { return; } if (mJustCreated) { // We need to start a query here the first time the activity is launched, as long // as we aren't doing a filter. //for bugzilla 12977 & 13021, delete the toast! /* if(Config.isMSMS){ for(int i=0;i<TelephonyManager.getPhoneCount();i++) simCardReadyToast(i); } else{ simCardReadyToast(); } */ startQuery(); } if(isDataChange && !mJustCreated){ startQuery(); isDataChange = false; } mJustCreated = false; mSearchInitiated = false; //bugId = 13920 ContentResolver resolver = getContentResolver(); if(mMode == MODE_STREQUENT){ Cursor starredCursor = resolver.query(STARRED_FREQUENT_URI, null, Contacts.STARRED + "=1", null, null); Log.d(TAG, "***************starredCursor = " + starredCursor.getCount()); if(starredCursor.getCount()<=0){ hasStarredContacts = false; }else{ hasStarredContacts = true; } if(null!=starredCursor){ starredCursor.close(); } Cursor frequentCursor = resolver.query(STARRED_FREQUENT_URI, null, Contacts.TIMES_CONTACTED + " > 0", null, null); Log.d(TAG,"***************frequentCursor = "+frequentCursor.getCount()); if(frequentCursor.getCount()<=0){ hasFreQuentContacts = false; }else{ hasFreQuentContacts = true; } if(null != frequentCursor){ frequentCursor.close(); } } } /** * Obtains the contacts provider status and configures the UI accordingly. * * @param loadData true if the method needs to start a query when the * provider is in the normal state * @return true if the provider status is normal */ private boolean checkProviderState(boolean loadData) { View importFailureView = findViewById(R.id.import_failure); if (importFailureView == null) { return true; } TextView messageView = (TextView) findViewById(R.id.emptyText); // This query can be performed on the UI thread because // the API explicitly allows such use. Cursor cursor = getContentResolver().query(ProviderStatus.CONTENT_URI, new String[] { ProviderStatus.STATUS, ProviderStatus.DATA1 }, null, null, null); try { if (cursor.moveToFirst()) { int status = cursor.getInt(0); if (status != mProviderStatus) { mProviderStatus = status; switch (status) { case ProviderStatus.STATUS_NORMAL: mAdapter.notifyDataSetInvalidated(); if (loadData) { startQuery(); } break; case ProviderStatus.STATUS_CHANGING_LOCALE: messageView.setText(R.string.locale_change_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADING: messageView.setText(R.string.upgrade_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY: long size = cursor.getLong(1); String message = getResources().getString( R.string.upgrade_out_of_memory, new Object[] {size}); messageView.setText(message); configureImportFailureView(importFailureView); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; } } } } finally { cursor.close(); } importFailureView.setVisibility( mProviderStatus == ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY ? View.VISIBLE : View.GONE); return mProviderStatus == ProviderStatus.STATUS_NORMAL; } private void configureImportFailureView(View importFailureView) { OnClickListener listener = new OnClickListener(){ public void onClick(View v) { switch(v.getId()) { case R.id.import_failure_uninstall_apps: { startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS)); break; } case R.id.import_failure_retry_upgrade: { // Send a provider status update, which will trigger a retry ContentValues values = new ContentValues(); values.put(ProviderStatus.STATUS, ProviderStatus.STATUS_UPGRADING); getContentResolver().update(ProviderStatus.CONTENT_URI, values, null, null); break; } } }}; Button uninstallApps = (Button) findViewById(R.id.import_failure_uninstall_apps); uninstallApps.setOnClickListener(listener); Button retryUpgrade = (Button) findViewById(R.id.import_failure_retry_upgrade); retryUpgrade.setOnClickListener(listener); } private String getTextFilter() { if (mSearchEditText != null) { return mSearchEditText.getText().toString(); } return null; } @Override protected void onRestart() { super.onRestart(); if (!checkProviderState(false)) { return; } // The cursor was killed off in onStop(), so we need to get a new one here // We do not perform the query if a filter is set on the list because the // filter will cause the query to happen anyway if (TextUtils.isEmpty(getTextFilter())) { //for bugzilla 12977 & 13021, delete the toast! /* if(Config.isMSMS){ for(int i=0;i<TelephonyManager.getPhoneCount();i++) simCardReadyToast(i); } else{ simCardReadyToast(); } */ startQuery(); } else { // Run the filtered query on the adapter mAdapter.onContentChanged(); } } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the QueryHandler has run if (mList != null) { icicle.putParcelable(LIST_STATE_KEY, mList.onSaveInstanceState()); } } @Override protected void onRestoreInstanceState(Bundle icicle) { super.onRestoreInstanceState(icicle); // Retrieve list state. This will be applied after the QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); } @Override protected void onStop() { super.onStop(); mBundle = null; mContactsPrefs.unregisterChangeListener(); if (null != mAdapter) { mAdapter.setSuggestionsCursor(null); mAdapter.changeCursor(null); } if (mMode == MODE_QUERY) { // Make sure the search box is closed SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.stopSearch(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the options menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return false; } MenuInflater inflater = getMenuInflater(); // MODE_ADD_CONTACTS_GROUP if(mContactsGroupNameId > -1) { inflater.inflate(R.menu.add_group_contact_list, menu); } else if(mMode == MODE_STREQUENT) { inflater.inflate(R.menu.remove_contacts, menu); } else { inflater.inflate(R.menu.list, menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if(mContactsGroupNameId > -1) { menu.findItem(R.id.menu_add_contact_to_group).setVisible(true); } else if(mMode == MODE_STREQUENT) { menu.findItem(R.id.remove_collection_contacts).setVisible(true); menu.findItem(R.id.remove_frequent_contacts).setVisible(true); Log.i(TAG, "hasStarredContacts=" + hasStarredContacts + " hasFreQuentContacts=" + hasFreQuentContacts); if(!hasStarredContacts){ menu.findItem(R.id.remove_collection_contacts).setEnabled(false); }else{ menu.findItem(R.id.remove_collection_contacts).setEnabled(true); } if(!hasFreQuentContacts){ menu.findItem(R.id.remove_frequent_contacts).setEnabled(false); }else{ menu.findItem(R.id.remove_frequent_contacts).setEnabled(true); } } else { final boolean defaultMode = (mMode == MODE_DEFAULT); menu.findItem(R.id.menu_display_groups).setVisible(defaultMode); boolean blackListVsb = CommonUtil.intentActionExist(this, Constants.ACTION_BLACK); menu.findItem(R.id.menu_blacklist).setVisible(blackListVsb); /*if(SyncSimContactsService.isWorking()){ Toast.makeText(this, R.string.service_is_busy, Toast.LENGTH_SHORT).show(); menu.findItem(R.id.menu_search).setEnabled(false); menu.findItem(R.id.menu_add).setEnabled(false); menu.findItem(R.id.menu_delete).setEnabled(false); menu.findItem(R.id.menu_import_export).setEnabled(false); // menu.findItem(R.id.menu_contacts_groups_add).setEnabled(false); menu.findItem(R.id.menu_memory_query).setEnabled(false); }else {*/ menu.findItem(R.id.menu_search).setEnabled(true); menu.findItem(R.id.menu_add).setEnabled(true); menu.findItem(R.id.menu_delete).setEnabled(true); menu.findItem(R.id.menu_import_export).setEnabled(true); // menu.findItem(R.id.menu_contacts_groups_add).setEnabled(true); menu.findItem(R.id.menu_memory_query).setEnabled(true); //} Log.i(TAG, "isEnableDeleteMenu="+isEnableDeleteMenu); menu.findItem(R.id.menu_delete).setEnabled(isEnableDeleteMenu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.remove_collection_contacts: { Intent intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_REMOVE_COLLECTION_CONTACTS); intent.putExtra("group", GROUP_ALL); startActivity(intent); return true; } case R.id.remove_frequent_contacts: { Intent intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_REMOVE_FREQUENT_CONTACTS); intent.putExtra("group", GROUP_ALL); startActivity(intent); return true; } case R.id.menu_add_contact_to_group: { Intent intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_ADD_CONTACTS_GROUP); intent.putExtra("group", GROUP_PHONE); intent.putExtra("mContactsGroupNameId", mContactsGroupNameId); intent.putExtra("mContactsGroupRingtone", mContactsGroupRingtone); startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); return true; } /** * bin.lai */ case R.id.menu_contacts_groups: this.startActivity(new Intent(this,ContactsGroupActivity.class)); return true; case R.id.menu_display_groups: { final Intent intent = new Intent(this, ContactsPreferencesActivity.class); startActivityForResult(intent, SUBACTIVITY_DISPLAY_GROUP); return true; } case R.id.menu_search: { onSearchRequested(); return true; } case R.id.menu_add: // by liaobz jump to simple-add view Intent newIntent = new Intent(this,GalleryPhoneEditActivity.class); newIntent.putExtra("mode", true); startActivity(newIntent); //createSelectAccountDialog(mContext, null, false).show(); return true; case R.id.menu_delete: displayContactsGroupDialog(item.getItemId()); return true; case R.id.menu_import_export: { displayImportExportDialog(); return true; } case R.id.menu_accounts: { final Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { ContactsContract.AUTHORITY }); startActivity(intent); return true; } case R.id.menu_memory_query: { final Intent intent = new Intent(this, ContactsMemoryActivity.class); intent.putExtra("phone_count", getPhoneContactsCount() ); //added for dual sim if(Config.isMSMS){ final TelephonyManager telManager = (TelephonyManager) getSystemService(PhoneFactory .getServiceName(Context.TELEPHONY_SERVICE, 0)); final TelephonyManager telManager2 = (TelephonyManager) getSystemService(PhoneFactory .getServiceName(Context.TELEPHONY_SERVICE, 1)); final boolean hasSim1 = (null != telManager) ? telManager.hasIccCard() : false; final boolean hasSim2 = (null != telManager2) ? telManager2.hasIccCard() : false; int simNum = 0; //the count of valid sim cards if (hasSim1 && simCardReady(0)) { intent.putExtra("sim_count1", String.valueOf(getSimContactsCount(0))); simNum++; } if (hasSim2 && simCardReady(1)) { intent.putExtra("sim_count2", String.valueOf(getSimContactsCount(1))); simNum++; } intent.putExtra("has_sim",simNum); } else{ if (simCardReady(false)) { intent.putExtra("has_sim",1); intent.putExtra("sim_count", getSimContactsCount()); }else{ intent.putExtra("has_sim",0); } } startActivity(intent); return true; } case R.id.menu_blacklist: { Intent blackIntent = new Intent(Constants.ACTION_BLACK); startActivity(blackIntent); return true; } } return false; } //fixed bugId:10326 public AlertDialog createSelectAccountDialog(final Context context, final String number, final boolean finish){ return createSelectAccountDialog(context, number,finish, -1); } public AlertDialog createSelectAccountDialog(final Context context, final String number, final boolean finish, final int requestCode){ ArrayList<Account> accounts = new ArrayList<Account>(); Account account = null; final TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); account = new Account(context.getString(R.string.contactsPhoneIconLabel), "Phone"); accounts.add(account); //added for dual sim if(Config.isMSMS){ final TelephonyManager telManager1 = (TelephonyManager) context.getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 0)); final TelephonyManager telManager2 = (TelephonyManager) context.getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); final boolean hasSim1 = (null != telManager1) ? telManager1.hasIccCard() : false; final boolean hasSim2 = (null != telManager2) ? telManager2.hasIccCard() : false; if (hasSim1 && telManager1.getSimState() == TelephonyManager.SIM_STATE_READY) { account = new Account(Account.SIM1_ACCOUNT_NAME, "Sim1"); accounts.add(account); } if (hasSim2 && telManager2.getSimState() == TelephonyManager.SIM_STATE_READY) { account = new Account(Account.SIM2_ACCOUNT_NAME, "Sim2"); accounts.add(account); } } else{ final boolean hasSim = (null != telManager) ? telManager.hasIccCard() : false; if (hasSim && telManager.getSimState() == TelephonyManager.SIM_STATE_READY) { account = new Account(context.getString(R.string.contactsSIMIconLabel), "Sim"); accounts.add(account); } } ArrayList<Account> accountsTemp = Sources.getInstance(context).getAccounts(true); if (!accountsTemp.isEmpty()) { int tempSize = accountsTemp.size(); for (int i = 0; i < tempSize; i++) { accounts.add(accountsTemp.get(i)); } } final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); final LayoutInflater dialogInflater = (LayoutInflater) dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final Sources sources = Sources.getInstance(context); final ArrayAdapter<Account> accountAdapter = new ArrayAdapter<Account>(context, android.R.layout.simple_list_item_2, accounts) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final TextView text1 = (TextView) convertView.findViewById(android.R.id.text1); final Account account = this.getItem(position); Log.i(TAG, "Account="+account.toString()); text1.setText(account.name); String displayLabel = null; if ("Phone".equals(account.type)) { displayLabel = account.name; } else if ("Sim".equals(account.type)) { displayLabel = "SIM"; } else if ("Sim1".equals(account.type)) { displayLabel = Account.SIM1_ACCOUNT_NAME; } else if ("Sim2".equals(account.type)) { displayLabel = Account.SIM2_ACCOUNT_NAME; }else { final ContactsSource source = sources.getInflatedSource(account.type, ContactsSource.LEVEL_SUMMARY); displayLabel = source.getDisplayLabel(context).toString(); } return convertView; } }; final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // Create new contact based on selected source final Account account = accountAdapter.getItem(which); if ("Sim".equals(account.type)) { if (!simCardReady(false)) { return; } else { createTo(1, account, context, number, finish, requestCode); } } else if ("Sim1".equals(account.type)) { if (!CommonUtil.isSimCardReady(0, false, mContext)) { Toast.makeText(context, R.string.sim1_notready_cant_not_save, Toast.LENGTH_LONG).show(); }else if(isSimInitializing(0)){ //sim1 is importing Toast.makeText(context, R.string.service_is_busy_sim1, Toast.LENGTH_SHORT).show(); } else if(telManager.getIccFdnEnabled()){ Toast.makeText(context, R.string.fdn_enable_nosetting, Toast.LENGTH_LONG).show(); //}else if(SyncSimContactsService.isWorking() && isSimInitializing(0)){ } else { createTo(1, account, context, number, finish, requestCode); } } else if ("Sim2".equals(account.type)) { final TelephonyManager telManager2 = (TelephonyManager) context.getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); //if (telManager2.getSimState() != TelephonyManager.SIM_STATE_READY) { if (!CommonUtil.isSimCardReady(1, false, mContext)) { Toast.makeText(context, R.string.sim2_notready_cant_not_save, Toast.LENGTH_LONG).show(); }else if(isSimInitializing(1)){ //sim1 is importing Toast.makeText(context, R.string.service_is_busy_sim2, Toast.LENGTH_SHORT).show(); } else if(telManager2.getIccFdnEnabled()){ Toast.makeText(context, R.string.fdn_enable_nosetting, Toast.LENGTH_LONG).show(); //}else if(SyncSimContactsService.isWorking() && isSimInitializing(1)){ } else { createTo(1, account, context, number, finish, requestCode); } } else if ("Phone".equals(account.type)) { createTo(0, null, context, number, finish, requestCode); } else { createTo(0, account, context, number, finish, requestCode); } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.dialog_new_contact_account); builder.setSingleChoiceItems(accountAdapter, 0, clickListener); return builder.create(); } /** * according where and account to get a intent for creating contact * * @param where 0:phone or google account e.g 1:SIM1 2:SIM2 * @param account * @param context * @param number create new contact with number * @param finish boolean finish pre-activity */ private static Intent getIntentForCreateToAccount(int where, Account account, Context context, final String number) { Intent intent = null; if (where == 0) { intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); if (null != account) { intent.putExtra(RawContacts.ACCOUNT_NAME, account.name); intent.putExtra(RawContacts.ACCOUNT_TYPE, account.type); } if (!TextUtils.isEmpty(number)) { intent.putExtra(Insert.PHONE, number); } if (mBundle != null) { intent.putExtras(mBundle); mBundle = null; } } else { intent = new Intent(Intent.ACTION_INSERT); intent.setClass(context, SimEditContactActivity.class); if("Sim".equals(account.type)){ boolean simFdnEnabled = SystemProperties.getBoolean("gsm.sim.fdn.enable", false); Log.d(TAG, "SIM FDN ENABLE = " + simFdnEnabled); if(simFdnEnabled){ Toast.makeText(context, R.string.fdn_enable_nosetting, Toast.LENGTH_SHORT).show(); return null; }else{ intent.putExtra(SimEditContactActivity.SIM_ADDRESS, SimEditContactActivity.SIM1_ADDRESS); intent.putExtra("mode", MODE_INSERT); } }else if("Sim1".equals(account.type)|| "Sim2".equals(account.type)){ intent.putExtra(SimEditContactActivity.SIM_ADDRESS, SimEditContactActivity.SIM1_ADDRESS); intent.putExtra("mode", MODE_INSERT); intent.putExtra("number", number); // intent.putExtra("account_name", account.name); } else{ intent.putExtra("mode", MODE_INSERT); intent.putExtra("account_name", account.name); } if (mBundle != null) { intent.putExtras(mBundle); mBundle = null; } } return intent; } /** * according where and account to start the activity * * @param where 0:phone or google account e.g 1:SIM1 2:SIM2 * @param account * @param context * @param number create new contact with number * @param finish boolean finish pre-activity * @param requestCode int requestCode If >= 0, this code will be returned in * onActivityResult() when the activity exits. */ private void createTo(int where, Account account, Context context, final String number, final boolean finish, int requestCode) { Intent intent = getIntentForCreateToAccount(where, account, context, number); if(requestCode<0){ context.startActivity(intent); } else{ startActivityForResult(intent, requestCode); } if (context instanceof Activity && finish) { ((Activity) context).finish(); } } /** * according where and account to start the activity * * @param where 0:phone or google account e.g 1:SIM1 2:SIM2 * @param account * @param context * @param number create new contact with number * @param finish boolean finish pre-activity */ private void createTo(int where, Account account, Context context, final String number, final boolean finish) { Intent intent = getIntentForCreateToAccount(where, account, context, number); context.startActivity(intent); if (context instanceof Activity && finish) { ((Activity) context).finish(); } } private static int getEmailNumber(String serviceName) { int mEmailNum = 0; IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager .getService(serviceName)); try { mEmailNum = iccIpb.getEmailNum(); } catch (RemoteException ex) { Log.v(TAG, "excetpion"); } catch (SecurityException ex) { Log.v(TAG, "excetpion"); } return mEmailNum; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return; } if (globalSearch) { super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } else { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0) { if ((mMode & MODE_MASK_PICKER) != 0) { ContactsSearchManager.startSearchForResult(this, initialQuery, SUBACTIVITY_FILTER); } else { ContactsSearchManager.startSearch(this, initialQuery); } } } } /** * Performs filtering of the list based on the search query entered in the * search text edit. */ protected void onSearchTextChanged() { Log.v(TAG, "onSearchTextChanged"); // Set the proper empty string //setEmptyText(); //yeezone:jinwei Filter filter = mAdapter.getFilter(); filter.filter(getTextFilter()); } /** * Starts a new activity that will run a search query and display search results. */ private void doSearch() { Log.v(TAG, "doSearch"); String query = getTextFilter(); Log.v(TAG, "query is " + query); if (TextUtils.isEmpty(query)) { return; } Intent intent = new Intent(this, SearchResultsActivity.class); Intent originalIntent = getIntent(); Bundle originalExtras = originalIntent.getExtras(); if (originalExtras != null) { intent.putExtras(originalExtras); } intent.putExtra(SearchManager.QUERY, query); if ((mMode & MODE_MASK_PICKER) != 0) { intent.setAction(ACTION_SEARCH_INTERNAL); intent.putExtra(SHORTCUT_ACTION_KEY, mShortcutAction); if (mShortcutAction != null) { if (Intent.ACTION_CALL.equals(mShortcutAction) || Intent.ACTION_SENDTO.equals(mShortcutAction)) { intent.putExtra(Insert.PHONE, query); } } else { switch (mQueryMode) { case QUERY_MODE_MAILTO: intent.putExtra(Insert.EMAIL, query); break; case QUERY_MODE_TEL: intent.putExtra(Insert.PHONE, query); break; } } startActivityForResult(intent, SUBACTIVITY_SEARCH); } else { intent.setAction(Intent.ACTION_SEARCH); startActivity(intent); } } @Override protected Dialog onCreateDialog(int id, Bundle bundle) { switch (id) { case R.string.import_from_sim: case R.string.import_from_sdcard: { return AccountSelectionUtil.getSelectAccountDialog(this, id); } case R.id.dialog_sdcard_not_found: { return new AlertDialog.Builder(this) .setTitle(R.string.no_sdcard_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.no_sdcard_message) .setPositiveButton(android.R.string.ok, null).create(); } case R.id.dialog_delete_contact_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_hide_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactWarning) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_multiple_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.multipleContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case DLG_ADD_BLACK: final String[] nums = bundle.getStringArray(ADD_BLACK_NUMBERS); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(R.string.blacklist); b.setCancelable(false); b.setItems(nums, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); removeDialog(DLG_ADD_BLACK); startAddBlackListActivity(nums[which]); } }); b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); removeDialog(DLG_ADD_BLACK); } }); return b.create(); } return super.onCreateDialog(id, bundle); } private void displayContactsGroupDialog(final int itemId) { // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); /** * bin.lai */ // Adapter that shows a list of string resources final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } //final int resId = this.getItem(position); final String resString = this.getItem(position); //((TextView)convertView).setText(resId); ((TextView)convertView).setText(resString); return convertView; } }; final Map<Integer, String> dividedNameMap = new HashMap<Integer, String>(); /** * bin.lai */ if(itemId == R.id.menu_contacts_groups){ Cursor cursor = this.getContentResolver().query(DIVIDED_GROUP_URI, null, null, null, null); String tmp; int id ; while(cursor.moveToNext()){ tmp = cursor.getString(cursor.getColumnIndexOrThrow("divided_name")); id = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)); dividedNameMap.put(id, tmp); adapter.add(tmp); } cursor.close(); } if(itemId!=R.id.menu_add){ adapter.add(getString(R.string.group_all)); } adapter.add(getString(R.string.group_phone)); //added for dual sim if (Config.isMSMS) { final TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); final TelephonyManager telManager2 = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); final boolean hasSim1 = (null != telManager) ? telManager.hasIccCard() : false; final boolean hasSim2 = (null != telManager2) ? telManager2.hasIccCard() : false; if (hasSim1 && telManager.getSimState() == TelephonyManager.SIM_STATE_READY) { adapter.add(getString(R.string.group_sim1)); } if (hasSim2 && telManager2.getSimState() == TelephonyManager.SIM_STATE_READY) { adapter.add(getString(R.string.group_sim2)); } } else { //modify by zhengshenglan for monkey test at 06-09 begin if(TelephonyManager.SIM_STATE_READY == ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getSimState()){ adapter.add(getString(R.string.group_sim)); } //modify by zhengshenglan for monkey test at 06-09 end } final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // for group final String resString = adapter.getItem(which); mContactsGroupNameId = -1; if(dividedNameMap.size() > 0){ for(Entry<Integer, String> tmp : dividedNameMap.entrySet()){ if(tmp.getValue() == resString){ mContactsGroupNameId = tmp.getKey(); } } } if (resString == getString(R.string.group_all)) { mPreContactsGroup = mContactsGroup; mContactsGroup=GROUP_ALL; } else if (resString == getString(R.string.group_phone)) { mPreContactsGroup = mContactsGroup; mContactsGroup=GROUP_PHONE; } else if (resString == getString(R.string.group_sim)) { if(!simCardReady(false)){ return; } mPreContactsGroup = mContactsGroup; mContactsGroup=GROUP_SIM; } else if (resString == getString(R.string.group_sim1)) { if(!CommonUtil.isSimCardReady(0, true, mContext)){ return; } if(isSimInitializing(0)){ Toast.makeText(ContactsListActivity.this, R.string.service_is_busy_sim1, Toast.LENGTH_SHORT).show(); return; } mPreContactsGroup = mContactsGroup; mContactsGroup=GROUP_SIM1; } else if (resString == getString(R.string.group_sim2)) { if(!CommonUtil.isSimCardReady(1, true, mContext)){ return; } if(isSimInitializing(1)){ Toast.makeText(ContactsListActivity.this, R.string.service_is_busy_sim2, Toast.LENGTH_SHORT).show(); return; } mPreContactsGroup = mContactsGroup; mContactsGroup=GROUP_SIM2; } else { Log.e(TAG, "Unexpected resource."); } //for operation switch (itemId) { case R.id.menu_add: { if(mContactsGroup==GROUP_PHONE){ final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); }else if(mContactsGroup==GROUP_SIM){ //yeezone:jinwei 2011-9-8 check before newing sim contacts String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); return; //or break; } IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager.getService("simphonebook")); int[] array = null; try{ array = iccIpb.getAdnRecordsSize(IccConstants.EF_ADN); }catch(RemoteException e){ //ignore it. } int simCount = getSimContactsCount(); if(array == null){ Toast.makeText(ContactsListActivity.this, R.string.get_sim_count_fail, Toast.LENGTH_LONG).show(); return; } int remainRecord = array[2]- simCount; Log.d(TAG, "remainRecord = " + remainRecord); if(remainRecord<1){ Toast.makeText(ContactsListActivity.this, R.string.toast_sim_overflow, Toast.LENGTH_LONG).show(); return; } startSimContactActivity(null, MODE_INSERT); }else if(mContactsGroup==GROUP_SIM1){ if(!checkSimStatus(0)){ return; } Intent intent=new Intent(Intent.ACTION_EDIT); intent.setClass(ContactsListActivity.this, SimEditContactActivity.class); intent.putExtra("mode", MODE_INSERT); intent.putExtra("account_name", Account.SIM1_ACCOUNT_NAME); startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); }else if(mContactsGroup==GROUP_SIM2){ if(!checkSimStatus(1)){ return; } Intent intent=new Intent(Intent.ACTION_EDIT); intent.setClass(ContactsListActivity.this, SimEditContactActivity.class); intent.putExtra("mode", MODE_INSERT); intent.putExtra("account_name", Account.SIM2_ACCOUNT_NAME); startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); } break; } case R.id.menu_delete: { //modify by dory.zheng for NEWMS00138007 begin if(!SimInitReceiver.isDelete){ Intent intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_DELETE); Log.i(TAG, "displayContactsGroupDialog, OnClickListener, menu_delete, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); }else{ Toast.makeText(ContactsListActivity.this, R.string.deleting, Toast.LENGTH_SHORT).show(); } //modify by dory.zheng for NEWMS00138007 end break; } //add by 2011-8-19 for 114329 begin case R.id.menu_contacts_groups: { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ContactsListActivity.this); prefs.edit().putInt("ContactsGroup", mContactsGroup).commit(); startQuery(); break; } //add by 2011-8-19 for 114329 end default: { Log.e(TAG, "Unexpected resource."); } } } }; new AlertDialog.Builder(this) .setTitle(R.string.select_contacts_group) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(adapter, -1, clickListener) .show(); } //added for dual sim private boolean checkSimStatus(int phoneId){ IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager.getService( PhoneFactory.getServiceName("simphonebook", phoneId))); int[] array = new int[3]; try{ array = iccIpb.getAdnRecordsSize(IccConstants.EF_ADN); }catch(RemoteException e){ //ignore it. } int simCount = getSimContactsCount(phoneId); int remainRecord = array[2]- simCount; Log.d(TAG, "checkSimStatus, remainRecord="+remainRecord); if(remainRecord<1){ Toast.makeText(ContactsListActivity.this, phoneId==0?R.string.toast_sim1_overflow:R.string.toast_sim2_overflow, Toast.LENGTH_LONG).show(); return false; } return true; } /** * Create a {@link Dialog} that allows the user to pick from a bulk import * or bulk export task across all contacts. */ private void displayImportExportDialog() { // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Adapter that shows a list of string resources final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final int resId = this.getItem(position); ((TextView)convertView).setText(resId); return convertView; } }; //added for dual sim if(Config.isMSMS){ final TelephonyManager telManager1 = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 0)); final TelephonyManager telManager2 = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); final boolean hasSim1 = (null != telManager1) ? telManager1.hasIccCard() : false; final boolean hasSim2 = (null != telManager2) ? telManager2.hasIccCard() : false; if (hasSim1 && telManager1.getSimState() == TelephonyManager.SIM_STATE_READY) { adapter.add(R.string.import_from_sim1); adapter.add(R.string.export_to_sim1); } if (hasSim2 && telManager2.getSimState() == TelephonyManager.SIM_STATE_READY) { adapter.add(R.string.import_from_sim2); adapter.add(R.string.export_to_sim2); } } else{ if (TelephonyManager.getDefault().hasIccCard()) { adapter.add(R.string.import_from_sim); adapter.add(R.string.export_to_sim); } } if (res.getBoolean(R.bool.config_allow_import_from_sdcard)) { adapter.add(R.string.import_from_sdcard); } if (res.getBoolean(R.bool.config_allow_export_to_sdcard)) { adapter.add(R.string.export_to_sdcard); } if (res.getBoolean(R.bool.config_allow_share_visible_contacts)) { adapter.add(R.string.share_visible_contacts); } final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent=null; String sim_oper_num = ""; final int resId = adapter.getItem(which); switch (resId) { case R.string.import_from_sim: if (!simCardReady(false)) { break; } //yeezone:jinwei 2011-9-9 sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); }else{ intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_IMPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, import_from_sim, mContactsGroup = " + GROUP_SIM); intent.putExtra("group", GROUP_SIM); startActivity(intent); } break; //added for dual sim case R.string.import_from_sim1: if(isFdnEnableDualSim(0)){ Log.d(TAG, "sim1 fdn is enable"); simCardFdnEableToast(0); return; } if(!CommonUtil.isSimCardReady(0, true, mContext)){ Log.d(TAG, "sim 0 is not ready"); break; } intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_IMPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, import_from_sim1, group = " + GROUP_SIM1); intent.putExtra("group", GROUP_SIM1); startActivity(intent); break; case R.string.import_from_sim2: if(isFdnEnableDualSim(1)){ Log.d(TAG, "sim1 fdn is enable"); simCardFdnEableToast(1); return; } if(! CommonUtil.isSimCardReady(1, true, mContext)){ Log.d(TAG, "sim 1 is not ready"); break; } intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_IMPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, import_from_sim2, group = " + GROUP_SIM2); intent.putExtra("group", GROUP_SIM2); startActivity(intent); break; case R.string.export_to_sim: if (!simCardReady(false)) { break; } // check sim card remain if (SimUtils.getSimRemain(ContactsListActivity.this, 0) <= 0) { Toast.makeText(ContactsListActivity.this, R.string.toast_sim_overflow, Toast.LENGTH_SHORT).show(); return; } String sim_oper_num1 = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num1 == null || sim_oper_num1.length() == 0){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); }else{ intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_EXPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, export_to_sim, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); startActivity(intent); } break; //added for dual sim case R.string.export_to_sim1: if(!CommonUtil.isSimCardReady(0, true, mContext)){ Log.d(TAG, "sim 0 is not ready"); break; } if(isFdnEnableDualSim(0)){ Log.d(TAG, "sim0 fdn is enable"); simCardFdnEableToast(0); break; } if (SimUtils.getSimRemain(ContactsListActivity.this, 0) <= 0) { Toast.makeText(ContactsListActivity.this, R.string.toast_sim1_overflow, Toast.LENGTH_SHORT).show(); return; } intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_EXPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, export_to_sim1, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); intent.putExtra("account_name", Account.SIM1_ACCOUNT_NAME); startActivity(intent); break; case R.string.export_to_sim2: if(!CommonUtil.isSimCardReady(1, true, mContext)){ Log.d(TAG, "sim 1 is not ready"); break; } if(isFdnEnableDualSim(1)){ Log.d(TAG, "sim1 fdn is enable"); simCardFdnEableToast(1); break; } if (SimUtils.getSimRemain(ContactsListActivity.this, 1) <= 0) { Toast.makeText(ContactsListActivity.this, R.string.toast_sim2_overflow, Toast.LENGTH_SHORT).show(); return; } intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_EXPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, export_to_sim2, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); intent.putExtra("account_name", Account.SIM2_ACCOUNT_NAME); startActivity(intent); break; case R.string.import_from_sdcard: { handleImportRequest(resId); break; } case R.string.export_to_sdcard: { /* Context context = ContactsListActivity.this; Intent exportIntent = new Intent(context, ExportVCardActivity.class); context.startActivity(exportIntent); break;*/ /** * shihaojie * */ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_SDCARD_EXPORT); Log.i(TAG, "displayImportExportDialog, OnClickListener, export_to_sdcard, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); //intent.putExtra("item", "export_to_sdcard"); startActivity(intent); } else{ showDialog(R.id.dialog_sdcard_not_found); } break; } case R.string.share_visible_contacts: { // doShareVisibleContacts(); intent=new Intent(Intent.ACTION_VIEW); intent.setClass(ContactsListActivity.this, MultiOperateListActivity.class); intent.putExtra("mode", MODE_BT_SHARE); Log.i(TAG, "displayImportExportDialog, OnClickListener, share_visible_contacts, mContactsGroup = " + mContactsGroup); intent.putExtra("group", mContactsGroup); startActivity(intent); break; } default: { Log.e(TAG, "Unexpected resource: " + getResources().getResourceEntryName(resId)); } } } }; new AlertDialog.Builder(this) .setTitle(R.string.dialog_import_export) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(adapter, -1, clickListener) .show(); } private void doShareVisibleContacts() { final Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI, sLookupProjection, getContactSelection(), null, null); try { if (!cursor.moveToFirst()) { Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show(); return; } StringBuilder uriListBuilder = new StringBuilder(); int index = 0; for (;!cursor.isAfterLast(); cursor.moveToNext()) { if (index != 0) uriListBuilder.append(':'); uriListBuilder.append(cursor.getString(0)); index++; } Uri uri = Uri.withAppendedPath( Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(uriListBuilder.toString())); final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(Contacts.CONTENT_VCARD_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(intent); } finally { cursor.close(); } } private void handleImportRequest(int resId) { // There's three possibilities: // - more than one accounts -> ask the user // - just one account -> use the account without asking the user // - no account -> use phone-local storage without asking the user final Sources sources = Sources.getInstance(this); final List<Account> accountList = sources.getAccounts(true); final int size = accountList.size(); if (size > 1) { showDialog(resId); return; } AccountSelectionUtil.doImport(this, resId, (size == 1 ? accountList.get(0) : null)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case SUBACTIVITY_NEW_CONTACT: if (resultCode == RESULT_OK) { //modify by dory.zheng for name is not display in link contacts begin Uri uri = data.getData(); String name = ""; try{ String contacts_id = uri.toString().substring(uri.toString().lastIndexOf("/") + 1); long id = Long.valueOf(contacts_id); name = getContactDisplayName(id); }catch (Exception e){ Log.d(TAG, " name is '' and uri is " + uri); } returnPickerResult(null, name, uri,(mMode & MODE_MASK_PICKER) != 0 ? Intent.FLAG_GRANT_READ_URI_PERMISSION : 0); /** returnPickerResult(null, data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME), data.getData(), (mMode & MODE_MASK_PICKER) != 0 ? Intent.FLAG_GRANT_READ_URI_PERMISSION : 0); */ } break; case SUBACTIVITY_VIEW_CONTACT: if (resultCode == RESULT_OK) { mAdapter.notifyDataSetChanged(); } break; case SUBACTIVITY_DISPLAY_GROUP: // Mark as just created so we re-run the view query mJustCreated = true; break; case SUBACTIVITY_FILTER: case SUBACTIVITY_SEARCH: // Pass through results of filter or search UI if (resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } break; case REQUEST_CODE_FOR_GROUP_ALL: //mContactsGroup = GROUP_ALL; yeezone:jinwei 2011-12-1 follow default mode //yeezone:jinwei 2011-12-9 restore previous group type Log.i(TAG,"REQUEST_CODE_FOR_GROUP_ALL, mContactsGroup:"+mContactsGroup+", mPreContactsGroup:"+mPreContactsGroup); //added for dual sim /* if(mContactsGroup==GROUP_PHONE){ mContactsGroup = mPreContactsGroup; }else if(mContactsGroup==GROUP_SIM ){ mContactsGroup = mPreContactsGroup; } */ if(GROUP_ALL!=mContactsGroup){ mContactsGroup = mPreContactsGroup; } break; } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the context menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return; } AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } long id = info.id; Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); long rawContactId = ContactsUtils.queryForRawContactId(getContentResolver(), id); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Whether it should display the item of removing the contacts from the common used contacts list. boolean isFrequent = ((ContactItemListAdapter) mAdapter).isFrequentPos(info.position); // Setup the menu header menu.setHeaderTitle(cursor.getString(getSummaryDisplayNameColumnIndex())); // View contact details final Intent viewContactIntent = new Intent(Intent.ACTION_VIEW, contactUri); StickyTabs.setTab(viewContactIntent, getIntent()); menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact) .setIntent(viewContactIntent); if (cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0) { // Calling contact menu.add(0, MENU_ITEM_CALL, 0, getString(R.string.menu_call)); if (SystemProperties.getBoolean("ro.device.support.vt", true)){ // Video Calling contact menu.add(0, MENU_ITEM_VIDEOCALL, 0, getString(R.string.menu_video_call)); } // Send SMS item menu.add(0, MENU_ITEM_SEND_SMS, 0, getString(R.string.menu_sendSMS)); } //modify by dory.zheng for add sim contacts to favorites begin int starState = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starState == 0) { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_addStar); } else { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_removeStar); } if (isFrequent) { menu.add(0, MENU_ITEM_REMOVE_FREQUENT, 0, R.string.menu_removeFrequent); } //modify by dory.zheng for add sim contacts to favorites end // Star toggling if(cursor.getInt(SUMMARY_SIM_COLUMN_INDEX)==0){ if(Config.isMSMS){ TelephonyManager telManager = (TelephonyManager) getSystemService(PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 0)); TelephonyManager telManager2 = (TelephonyManager) getSystemService(PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); if(telManager != null && telManager.hasIccCard() && telManager.getSimState() == TelephonyManager.SIM_STATE_READY){ menu.add(0, MENU_ITEM_EXPORT_TO_SIM1, 0, R.string.export_to_sim1); } if(telManager2 != null && telManager2.hasIccCard() && telManager2.getSimState() == TelephonyManager.SIM_STATE_READY){ menu.add(0, MENU_ITEM_EXPORT_TO_SIM2, 0, R.string.export_to_sim2); } } else{ menu.add(0, MENU_ITEM_EXPORT, 0, R.string.export_to_sim); } } else { menu.add(0, MENU_ITEM_IMPORT, 0, R.string.import_to_phone); } // Contact editing menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact) .setIntent(new Intent(Intent.ACTION_EDIT, rawContactUri)); menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact); //add by 2011-8-19 for 114329 begin int account_name_id = cursor.getColumnIndexOrThrow("account_name"); String account_name = cursor.getString(account_name_id); Log.d(TAG, "account_name = "+account_name); if(account_name == null){ menu.add(0, MENU_ITEM_DIVIDED_GROUP,0,R.string.divided_group_to); } if(account_name != null){ if(!account_name.equals("SIM") && !account_name.equals("SIM1") && !account_name.equals("SIM2")){ menu.add(0, MENU_ITEM_DIVIDED_GROUP,0,R.string.divided_group_to); } } if (mContactsGroupNameId != -1) {// from group menu.add(0, MENU_ITEM_REMOVE_CONTACTS_FROM_GROUP, 0, R.string.remove_contacts_from_group); } //add by 2011-8-19 for 114329 end /* fixed CR<NEWMS00120798> by luning at 2011.11.08*/ menu.add(0, MENU_ITEM_SHARE_BY_SMS, 0, R.string.share_by_sms); menu.add(0, MENU_ITEM_SHARE_BY_MMS, 0, R.string.share_by_mms); if(SystemProperties.getBoolean(PROPERTY_RO_DEVICE_SUPPORT_BT, true)) { menu.add(0, MENU_ITEM_SHARE_BY_BLUETOOTH, 0, R.string.share_by_bluetooth); } menu.add(0, MENU_ITEM_SHARE_BY_EMAIL, 0, R.string.share_by_email); if (CommonUtil.intentActionExist(this, Constants.ACTION_BLACK)) { menu.add(0, MENU_ITEM_ADD_BLACK, 0, getString(R.string.blacklist_add)); } } /** * bin.lai */ private void showDividedGroup(final int contact_id){ final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Adapter that shows a list of string resources final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } //this.getItem(position). //final int resId = (Integer)this.getItem(position); ((TextView)convertView).setText((String)this.getItem(position)); return convertView; } }; Cursor cursor = this.getContentResolver().query(DIVIDED_GROUP_URI, null, null, null, null); String tmp; int groupId; while(cursor.moveToNext()){ tmp = cursor.getString(cursor.getColumnIndexOrThrow("divided_name")); groupId = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)); if(groupId < 4 && groupId > -1){ tmp = getDeafaultGroupName(groupId, tmp); } adapter.add(tmp); } cursor.close(); AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(R.string.select_contacts_group) .setNegativeButton(android.R.string.cancel, null); if (adapter.getCount() > 0 ){ final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); String name = adapter.getItem(which); ContentResolver resolver = getContentResolver(); int id = -1; String customGroupRingtone = null; Log.v(TAG, "divided_group_name:" + name); Cursor cursor = resolver.query(DIVIDED_GROUP_URI, null, "divided_name=?", new String[]{name}, null); while(cursor.moveToNext()){ id = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)); customGroupRingtone = cursor.getString(cursor.getColumnIndexOrThrow("divided_ringtone")); // case R.id.menu_contacts_groups: { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ContactsListActivity.this); // prefs.edit().putInt("ContactsGroup", mContactsGroup).commit(); // startQuery(); // break; // } Log.v(TAG, "group_nam_id:" + id); } cursor.close(); // divided_group_name_id if(id != -1){ ContentValues contentValues = new ContentValues(); contentValues.put("divided_group_name_id", id); contentValues.put("custom_group_ringtone", customGroupRingtone); int success = resolver.update(Uri.parse("content://"+ContactsContract.AUTHORITY+"/raw_contacts"), contentValues, "contact_id = ?", new String[]{String.valueOf(contact_id)}); Log.d(TAG, "success = " + success); if(success > -1) { Toast.makeText(mContext, R.string.add_to_group_success, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, R.string.add_to_group_fail, Toast.LENGTH_SHORT).show(); } } // update table raw_contact set divided_group_name_id = id where raw_contact._id = ? } }; builder.setSingleChoiceItems(adapter, -1, clickListener); } else { String str = getString(R.string.no_contacts_group_name) + "," + getString(R.string.please_add_group); builder.setMessage(str); } builder.show(); } private String getDeafaultGroupName(int groupNameId, String tmp){ String groupName = ""; ContentValues values = new ContentValues(); switch(groupNameId){ case GROUP_NAME_STUDENT: groupName = mContext.getString(R.string.group_name_student); break; case GROUP_NAME_FRIEND: groupName = mContext.getString(R.string.group_name_friend); break; case GROUP_NAME_FAMILY: groupName = mContext.getString(R.string.group_name_family); break; case GROUP_NAME_COLLEAGUE: groupName = mContext.getString(R.string.group_name_colleague); break; default: break; } values.put("divided_name", groupName); if(!tmp.equals(groupName)) { mContext.getContentResolver().update(DIVIDED_GROUP_URI, values, "_id=" + groupNameId, null); return groupName; } else { return tmp; } } /** * remove contact from group dialog * * @param raw_contactId */ private void showRemoveContactFromGroup(int raw_contactId) { final int contact_id = raw_contactId; new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.remove_contacts_from_group) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); ContentResolver resolver = getContentResolver(); ContentValues contentValues = new ContentValues(); contentValues.put("divided_group_name_id", -1); contentValues.put("custom_group_ringtone", ""); resolver.update(Uri.parse("content://"+ ContactsContract.AUTHORITY+ "/raw_contacts"), contentValues, "contact_id = ?", new String[] { String .valueOf(contact_id) }); } }).show(); } //added for dual sim private boolean exportContactToSim(Cursor cursor, int phoneId){ if(!simCardReady(phoneId)){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); return true; } if(isFdnEnableDualSim(phoneId)){ Log.d(TAG, "sim" + phoneId + " fdn is enable"); simCardFdnEableToast(phoneId); return true; } int anrCount = 0; int emailCount = 0; IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface( ServiceManager.getService(PhoneFactory.getServiceName("simphonebook", phoneId))); try { anrCount = iccIpb.getAnrNum(); emailCount = iccIpb.getEmailNum(); } catch (RemoteException ex) { Log.v(TAG,"excetpion"); } catch (SecurityException ex) { Log.v(TAG,"excetpion"); } ArrayList<Usimphonestruct> usimContactsMap = getAllExportDataPhoneNum(cursor, anrCount + 1, emailCount, phoneId); String phoneHome = ""; String phoneMobile = ""; String phoneWork = ""; String phoneOther = ""; String email = ""; String name = ""; name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX); name = getTagNAME(name,phoneId); //for add Contacts, the name length max 14 for (int i=0; i< usimContactsMap.size(); i++) { phoneHome = usimContactsMap.get(i).phonenumber; phoneMobile = usimContactsMap.get(i).anr1; phoneWork = usimContactsMap.get(i).anr2; phoneOther = usimContactsMap.get(i).anr3; email = usimContactsMap.get(i).email; name = usimContactsMap.get(i).name; Log.d(TAG, "export to sim: name="+name+", phoneHome="+phoneHome +", phoneMobile="+phoneMobile + ", phoneWork="+phoneWork + ", phoneOther="+phoneOther + ", email="+email+", phoneId="+phoneId); String anr = phoneMobile + AdnRecord.ANR_SPLIT_FLG + phoneWork + AdnRecord.ANR_SPLIT_FLG + phoneOther; String newAnr = ""; String mSimNewAnr = ""; if (anrCount > 0) { mSimNewAnr = phoneMobile; newAnr = phoneMobile + AdnRecord.ANR_SPLIT_FLG +AdnRecord.ANR_SPLIT_FLG; if (anrCount > 1) { mSimNewAnr += AdnRecord.ANR_SPLIT_FLG + phoneWork; newAnr = phoneMobile + AdnRecord.ANR_SPLIT_FLG + phoneWork + AdnRecord.ANR_SPLIT_FLG; if (anrCount > 2) { mSimNewAnr = anr; newAnr = anr; } } } if((name == null || name.length() == 0) && (phoneHome == null || phoneHome.length() == 0) && (phoneMobile == null || phoneMobile.length() == 0) && (phoneWork == null || phoneWork.length() == 0) && (phoneOther == null || phoneOther.length() == 0) && (email == null || email.length() == 0)){ Toast.makeText(this, R.string.number_empty, Toast.LENGTH_SHORT).show(); return true; } if(emailCount == 0){ email = ""; } if(anrCount == 0 && emailCount == 0 && name.equals("") && phoneHome.equals("")){ Toast.makeText(this, R.string.exprot_fail_only_email, Toast.LENGTH_SHORT).show(); return true; } ContentValues cv = new ContentValues(); cv.put("newTag", name); cv.put("newNumber", phoneHome); // cv.put("anr", mSimNewAnr); cv.put("newAnr", newAnr); cv.put("newEmail", email); if(0==phoneId){ cv.put("account_type", Account.SIM_ACCOUNT_TYPE); cv.put("account_name", Account.SIM1_ACCOUNT_NAME); } else{ cv.put("account_type", Account.SIM_ACCOUNT_TYPE); cv.put("account_name", Account.SIM2_ACCOUNT_NAME); } Log.d(TAG, "name=="+cv.getAsString("newTag") +"|newNumber=="+cv.getAsString("newNumber") +"|anr=="+cv.getAsString("anr")+"|newSimAnr=="+cv.getAsString("newSimAnr") +"|email=="+cv.getAsString("email")); if(getContentResolver().insert(getSimUri(), cv) != null){ Toast.makeText(this, phoneId==0?R.string.export_sim1_success:R.string.export_sim2_success, Toast.LENGTH_SHORT).show(); }else{ if(CommonUtil.getFreeCapacity(this, phoneId) < 1){ Toast.makeText(this, phoneId==0?R.string.toast_sim1_overflow:R.string.toast_sim2_overflow, Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, phoneId==0?R.string.export_sim1_fail:R.string.export_sim2_fail, Toast.LENGTH_SHORT).show(); } } } if(usimContactsMap == null || usimContactsMap.size() == 0){ ContentValues cv = new ContentValues(); cv.put("newTag", name); cv.put("newNumber", ""); cv.put("newAnr", ""); // cv.put("newSimAnr", ""); cv.put("newEmail", ""); if(0==phoneId){ cv.put("account_type", Account.SIM_ACCOUNT_TYPE); cv.put("account_name", Account.SIM1_ACCOUNT_NAME); } else{ cv.put("account_type", Account.SIM_ACCOUNT_TYPE); cv.put("account_name", Account.SIM2_ACCOUNT_NAME); } if(getContentResolver().insert(getSimUri(), cv) != null){ Toast.makeText(this, phoneId==0?R.string.export_sim1_success:R.string.export_sim2_success, Toast.LENGTH_SHORT).show(); }else{ if(CommonUtil.getFreeCapacity(this, phoneId) < 1){ Toast.makeText(this, phoneId==0?R.string.toast_sim1_overflow:R.string.toast_sim2_overflow, Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, phoneId==0?R.string.export_sim1_fail:R.string.export_sim2_fail, Toast.LENGTH_SHORT).show(); } } } return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); switch (item.getItemId()) { case MENU_ITEM_REMOVE_CONTACTS_FROM_GROUP: int raw_contactId = cursor.getInt(cursor .getColumnIndexOrThrow(BaseColumns._ID)); Log.i(TAG, "raw_contactId="+raw_contactId); showRemoveContactFromGroup(raw_contactId); return true; case MENU_ITEM_DIVIDED_GROUP:{ int raw_contact_id = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)); showDividedGroup(raw_contact_id); return true; } case MENU_ITEM_VIEW_CONTACT: { //if(cursor.getInt(SUMMARY_SIM_COLUMN_INDEX)!=0){ // startSimContactActivity(cursor, MODE_VIEW); // return true; //} break; } case MENU_ITEM_TOGGLE_STAR: { // Toggle the star ContentValues values = new ContentValues(1); values.put(Contacts.STARRED, cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX) == 0 ? 1 : 0); final Uri selectedUri=ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getInt(SUMMARY_ID_COLUMN_INDEX)); getContentResolver().update(selectedUri, values, null, null); return true; } case MENU_ITEM_SEND_SMS: { smsContact(cursor); return true; } //added for dual sim case MENU_ITEM_EXPORT_TO_SIM1: return(exportContactToSim(cursor,0)); case MENU_ITEM_EXPORT_TO_SIM2: return(exportContactToSim(cursor,1)); //modify by zhengshenglan for NEWMS00118626 at 08-28 begin case MENU_ITEM_EXPORT: { if(!simCardReady(false)){ return true; } String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); return true; } int phonenumbercount = 0; int emailcount = 0; IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface( ServiceManager.getService("simphonebook")); try { phonenumbercount = iccIpb.getAnrNum(); emailcount = iccIpb.getEmailNum(); } catch (RemoteException ex) { Log.v(TAG,"excetpion"); } catch (SecurityException ex) { Log.v(TAG,"excetpion"); } ArrayList<Usimphonestruct> usimContactsMap = getAllExportDataPhoneNum(cursor, phonenumbercount + 1, emailcount, 0); String phoneHome = ""; String phoneMobile = ""; String phoneWork = ""; String phoneOther = ""; String email = ""; String name = ""; name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX); name = getTagNAME(name); //for add Contacts, the name length max 14 for (int i=0; i< usimContactsMap.size(); i++) { phoneHome = usimContactsMap.get(i).phonenumber; phoneMobile = usimContactsMap.get(i).anr1; phoneWork = usimContactsMap.get(i).anr2; phoneOther = usimContactsMap.get(i).anr3; email = usimContactsMap.get(i).email; name = usimContactsMap.get(i).name; Log.d(TAG, "export to sim >>> name==="+name+"phoneHome==="+phoneHome +" phoneMobile==="+phoneMobile + " phoneWork==="+phoneWork + " phoneOther==="+phoneOther + " email==="+email); String anr = phoneMobile+AdnRecord.ANR_SPLIT_FLG+phoneWork+AdnRecord.ANR_SPLIT_FLG+phoneOther; String newAnr = ""; String mSimNewAnr = ""; if (phonenumbercount > 0) { //1 mSimNewAnr = phoneMobile; newAnr = phoneMobile + AdnRecord.ANR_SPLIT_FLG + AdnRecord.ANR_SPLIT_FLG; if (phonenumbercount > 1) { //2 mSimNewAnr += AdnRecord.ANR_SPLIT_FLG + phoneWork; newAnr = phoneMobile + AdnRecord.ANR_SPLIT_FLG + phoneWork + AdnRecord.ANR_SPLIT_FLG; if (phonenumbercount > 2) { // mSimNewAnr = anr; newAnr = anr; } } } if((name == null || name.length() == 0) && (phoneHome == null || phoneHome.length() == 0) && (phoneMobile == null || phoneMobile.length() == 0) && (phoneWork == null || phoneWork.length() == 0) && (phoneOther == null || phoneOther.length() == 0) && (email == null || email.length() == 0)){ Toast.makeText(this, R.string.number_empty, Toast.LENGTH_SHORT).show(); return true; } if(emailcount == 0){ email = ""; } //modify by dory.zheng for export to sim empty record begin if(phonenumbercount == 0 && emailcount == 0 && name.equals("") && phoneHome.equals("")){ Toast.makeText(this, R.string.exprot_fail_only_email, Toast.LENGTH_SHORT).show(); return true; } //modify by dory.zheng for exoprt to sim empty record end ContentValues cv = new ContentValues(); cv.put("newTag", name); cv.put("newNumber", phoneHome); // cv.put("anr", mSimNewAnr); cv.put("newAnr", newAnr); cv.put("newEmail", email); Log.d(TAG, "name=="+cv.getAsString("newTag") +"|newNumber=="+cv.getAsString("newNumber") +"|anr=="+cv.getAsString("anr")+"|newSimAnr=="+cv.getAsString("newSimAnr") +"|email=="+cv.getAsString("email")); if (getContentResolver().insert(getSimUri(), cv) != null) { Toast.makeText(this, R.string.export_sim_success, Toast.LENGTH_SHORT) .show(); } else if (SimUtils.getSimRemain(this, 0) <= 0) { Toast.makeText(this, R.string.toast_sim_overflow, Toast.LENGTH_SHORT) .show(); break; } else { Toast.makeText(this, R.string.export_sim_fail, Toast.LENGTH_SHORT).show(); break; } } if(usimContactsMap.size() == 0){ ContentValues cv = new ContentValues(); cv.put("newTag", name); cv.put("newNumber", ""); // cv.put("anr", ""); cv.put("newAnr", ""); cv.put("newEmail", ""); if (getContentResolver().insert(getSimUri(), cv) != null) { Toast.makeText(this, R.string.export_sim_success, Toast.LENGTH_SHORT) .show(); } else if (SimUtils.getSimRemain(this, 0) <= 0) { Toast.makeText(this, R.string.toast_sim_overflow, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, R.string.export_sim_fail, Toast.LENGTH_SHORT).show(); } } return true; } case MENU_ITEM_IMPORT: { if(!Config.isMSMS){ if(!simCardReady(false)){ return true; } } //modify by zhengshenglan at 08-24 begin // String name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX); String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } String name = queryPhoneName(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); ArrayList<String> contactsList = getAllDataPhoneNum(cursor); contactsList.add(name); /* ContentValues cv = new ContentValues(); cv.put("name", name); if(phoneOrEmail != null){ cv.put("phoneHome", phoneOrEmail.get(0)); cv.put("phoneMobile", phoneOrEmail.get(1)); cv.put("phoneWork", phoneOrEmail.get(2)); cv.put("phoneOther", phoneOrEmail.get(3)); cv.put("email", phoneOrEmail.get(4)); } actuallyImportOneSimContact(cv); */ actuallyImportOneSimContact(contactsList); return true; } case MENU_ITEM_EDIT: { if(cursor.getInt(SUMMARY_SIM_COLUMN_INDEX)!=0){ startSimContactActivity(cursor, MODE_EDIT); return true; } break; } case MENU_ITEM_DELETE: { //modify by dory.zheng for NEWMS00138007 begin if(!SimInitReceiver.isDelete){ if(cursor.getInt(SUMMARY_SIM_COLUMN_INDEX)!=0){ String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); //added for dual sim begin if(Config.isMSMS){ Log.d(TAG, "menu item delete accountName = "+accountName); int phoneId = -1; if(accountName.equals(Account.SIM1_ACCOUNT_NAME)){ phoneId = 0; }else if(accountName.equals(Account.SIM2_ACCOUNT_NAME)){ phoneId = 1; } if(phoneId <0){ Log.e(TAG, "phoneID error in menu delete "); return true; } if(isFdnEnableDualSim(phoneId)){ Log.d(TAG, "phone " + phoneId + " fdn is enable"); return true; } if(!simCardReady(phoneId)){ Log.d(TAG, "phone " + phoneId + "is not ready"); return true; } } new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteSimClickListener(cursor.getString(SUMMARY_SIM_COLUMN_INDEX), accountName)).show(); return true; } mSelectedContactUri = getContactUri(info.position); doContactDelete(mSelectedContactUri); return true; }else{ Toast.makeText(ContactsListActivity.this, R.string.deleting, Toast.LENGTH_SHORT).show(); return true; } //modify by dory.zheng for NEWMS00138007 end } // remove the contact from common used contact list. case MENU_ITEM_REMOVE_FREQUENT: ContentValues values = new ContentValues(1); values.put(Contacts.TIMES_CONTACTED, 0); final Uri selectedUri = this.getContactUri(info.position); getContentResolver().update(selectedUri, values, null, null); return true; /** * yeezone.shihaojie * add to firewall */ case MENU_ITEM_ADD_TO_FIRE_WALL:{ String AddFirePhoneNum= getPhoneNum(cursor); Log.v(TAG, "AddPhoneNum = " + AddFirePhoneNum); if(AddFirePhoneNum.equals("")) { Toast.makeText(ContactsListActivity.this, R.string.contactslist_menu_addto_firewall_null, Toast.LENGTH_SHORT).show(); } else { Intent addfirewall = new Intent(); Bundle bundle = new Bundle(); bundle.putString("Click_BlackCalls_Number", AddFirePhoneNum); bundle.putInt("Click_BlackCalls_Type", 0); addfirewall.putExtras(bundle); addfirewall.setAction("com.yeezonetech.firewall.ui.BlackCallsListAddActivity.action"); startActivity(addfirewall); } } case MENU_ITEM_CALL: { callContact(cursor); return true; } case MENU_ITEM_VIDEOCALL: { videocallContact(cursor); return true; } // ===== fixed CR<NEWMS00120798> by luning at 2011.11.08 begin ===== case MENU_ITEM_SHARE_BY_SMS: case MENU_ITEM_SHARE_BY_MMS: { ArrayList<String> usimPhone = new ArrayList<String>(); ArrayList<String> usimEmail = new ArrayList<String>(); Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } String name = queryPhoneName(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); //added for dual sim if(Config.isMSMS){ String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index, accountName); } else{ phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); } try { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { String type = phonesCursor.getString(phonesCursor .getColumnIndex(Data.MIMETYPE)); String data = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); if (Phone.CONTENT_ITEM_TYPE.equals(type)) { usimPhone.add(data); } else if (Email.CONTENT_ITEM_TYPE.equals(type)) { usimEmail.add(data); } } } catch (Exception e) { e.printStackTrace(); } finally { if (phonesCursor != null) { phonesCursor.close(); } } StringBuilder sb = new StringBuilder(); sb.append(getString(R.string.conatcts_name) + ":"); sb.append('\n'); sb.append(" " + name); sb.append('\n'); if (usimPhone.size() > 0) { sb.append(getString(R.string.phone_number) + ":"); sb.append('\n'); for (String number : usimPhone) { sb.append(" " + number); sb.append('\n'); } } if (usimEmail.size() > 0) { Log.d(TAG, "usimEmail.size():"+usimEmail.size()); sb.append(getString(R.string.concacts_email) + ":"); sb.append('\n'); for (String email : usimEmail) { sb.append(" " + email); sb.append('\n'); } } if (item.getItemId() == MENU_ITEM_SHARE_BY_SMS) {/*send by SMS*/ Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts( "sms", "", null)); intent.putExtra("sms_body", sb.toString()); startActivity(intent); } else if(item.getItemId() == MENU_ITEM_SHARE_BY_MMS){/*send by MMS*/ final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); String lookupKey = cursor .getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); Uri lookupUri = Contacts.getLookupUri(contactId, lookupKey); lookupKey = Uri.encode(lookupUri.getPathSegments().get(2)); final Uri shareUri = Uri.withAppendedPath( Contacts.CONTENT_VCARD_URI, lookupKey); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts( "mms", "", null)); intent.putExtra("share_contact_uri", shareUri.toString()); if (TextUtils.isEmpty(name)) { name = getString(android.R.string.unknownName); } intent.putExtra("name", name.replaceAll("/", "_")); intent.putExtra("detail", sb.toString()); startActivity(intent); } return true; } case MENU_ITEM_ADD_BLACK: {// Fixed bug 4474 by phone_07, 2011.10.24 ArrayList<String> usimPhone = new ArrayList<String>(); ArrayList<String> usimEmail = new ArrayList<String>(); Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } String name = queryPhoneName(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); //added for dual sim if(Config.isMSMS){ String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index, accountName); } else{ phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); } try { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { String type = phonesCursor.getString(phonesCursor .getColumnIndex(Data.MIMETYPE)); String data = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); if (Phone.CONTENT_ITEM_TYPE.equals(type)) { usimPhone.add(data); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (phonesCursor != null) { phonesCursor.close(); } } String num = ""; if(usimPhone.size() == 0){ Toast.makeText(ContactsListActivity.this, getString(R.string.blacklist_no_number), Toast.LENGTH_SHORT).show(); }else if(usimPhone.size() == 1){ num = usimPhone.get(0); startAddBlackListActivity(num); }else{ Bundle bundle = new Bundle(); bundle.putStringArray(ADD_BLACK_NUMBERS, usimPhone.toArray(new String[usimPhone.size()])); showDialog(DLG_ADD_BLACK, bundle); } return true; } // ===== fixed CR<NEWMS00120798> by luning at 2011.11.08 end ===== case MENU_ITEM_SHARE_BY_BLUETOOTH: case MENU_ITEM_SHARE_BY_EMAIL: final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); sendVcard(this, Contacts.getLookupUri(contactId, lookupKey), getContactDisplayName(contactId), item.getItemId()); return true; } if(cursor != null){ cursor.close(); } return super.onContextItemSelected(item); } /** * send contacts information by vcard * * @param context * @param lookupUri contacts's lookupUri * @param name contacts'name */ public void sendVcard(Context context, Uri lookupUri, String name, int itemId) { String lookupKey = Uri.encode(lookupUri.getPathSegments().get(2)); final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); Intent it = new Intent(Intent.ACTION_SEND); it.setType(Contacts.CONTENT_VCARD_TYPE); it.putExtra(Intent.EXTRA_STREAM, shareUri); if(itemId == MENU_ITEM_SHARE_BY_BLUETOOTH) { it.setClassName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity"); } else if(itemId == MENU_ITEM_SHARE_BY_EMAIL) { it.setClassName("com.android.email", "com.android.email.activity.MessageCompose"); } if (TextUtils.isEmpty(name)) { name = context.getString(android.R.string.unknownName); } it.putExtra("name", name.replaceAll("/", "_")); try{ context.startActivity(it); }catch(ActivityNotFoundException ex){ Log.d(TAG, "ActivityNotFoundException: " + ex.toString()); } } /** * Start add black list activity * * @author phone_07 * @param number phone number */ private void startAddBlackListActivity(String number) { Intent intent = new Intent(Constants.ACTION_ADD_BLACKLIST); intent.putExtra("Click_BlackCalls_Number", number); startActivity(intent); } // add by niezhong 08-30-11 for NEWMS00118868 begin private String getTagNAME(String tagName) { return getTagNAME(tagName,0); } private String getTagNAME(String tagName,int phoneId) { IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager.getService(PhoneFactory.getServiceName("simphonebook", phoneId))); int[] adnRecords = new int[]{}; try { adnRecords = iccIpb.getAdnRecordsSize(IccConstants.EF_ADN); } catch (RemoteException ex) { Log.v(TAG, "excetpion"); } catch (SecurityException ex) { Log.v(TAG, "excetpion"); } final int nameSize = adnRecords[0] - 14; int sCount = 0; try { sCount = GsmAlphabet.countGsmSeptets(tagName, true,true); } catch (EncodeException e) { // TODO Auto-generated catch block sCount = tagName.length() * 2; int size = (nameSize - 1 ) / 2; if (sCount > size * 2) { tagName = (tagName.subSequence(0, size)).toString(); } return tagName; } if (sCount > nameSize) { //modify by dory.zheng for add Contacts, the name length max 14 begin StringBuffer tempName = new StringBuffer(); int tempSize = nameSize; char[] tagNameArray = tagName.toCharArray(); for (char c : tagNameArray){ if(GsmAlphabet.charToGsmExtended(c) != 32){ tempSize -= 2; } else { tempSize -= 1; } if(tempSize < 0) break; tempName.append(c); } tagName = tempName.toString(); // tagName = (tagName.subSequence(0, 14)).toString(); //modify by dory.zheng for add Contacts, the name length max 14 end } return tagName; } // add by niezhong 08-30-11 for NEWMS00118868 end //modify by zhengshenglan at 08-24 begin // private void actuallyImportOneSimContact(ContentValues cv) { private void actuallyImportOneSimContact(ArrayList<String> list) { /*String name = cv.getAsString("name"); String phoneHome = cv.getAsString("phoneHome"); String phoneMobile = cv.getAsString("phoneMobile"); String phoneWork = cv.getAsString("phoneWork"); String phoneOther = cv.getAsString("phoneOther"); String email = cv.getAsString("email");*/ String phoneHome = list.get(0); String phoneMobile = list.get(1); String phoneWork = list.get(2); String phoneOther = list.get(3); String email = list.get(4); String name = list.get(5); Log.d(TAG, "name:"+name+";phoneMobile:"+phoneMobile+";phoneHome:" +phoneHome+";phoneWork:"+phoneWork+";phoneOther:"+phoneOther +";email:"+email); String[] otherPhoneNumber = {phoneMobile, phoneWork , phoneOther}; final ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI); builder.withValues(new ContentValues()); operationList.add(builder.build()); //add name if(name != null && !"".equals(name)){ builder = ContentProviderOperation.newInsert(Data.CONTENT_URI); builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0); builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); builder.withValue(StructuredName.GIVEN_NAME, name); operationList.add(builder.build()); } //add phoneMobile if(phoneHome != null && !"".equals(phoneHome)){ builder = ContentProviderOperation.newInsert(Data.CONTENT_URI); builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0); builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); builder.withValue(Phone.TYPE, Phone.TYPE_HOME); builder.withValue(Phone.NUMBER, phoneHome); builder.withValue(Data.IS_PRIMARY, 1); operationList.add(builder.build()); } //add otherPhoneNumber if (otherPhoneNumber != null) { for(int i = 0;i<otherPhoneNumber.length;i++){ if (otherPhoneNumber[i] != null && !"".equals(otherPhoneNumber[i])) { builder = ContentProviderOperation .newInsert(Data.CONTENT_URI); builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0); builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); builder.withValue(Phone.TYPE, NUMBERTYPE[i]); builder.withValue(Phone.NUMBER, otherPhoneNumber[i]); builder.withValue(Data.IS_PRIMARY, 1); operationList.add(builder.build()); Log.d(TAG, NUMBERTYPE[i] + "=" + otherPhoneNumber[i]); } } } //add email if(email != null && !"".equals(email)){ builder = ContentProviderOperation.newInsert(Data.CONTENT_URI); builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0); builder.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); builder.withValue(Email.TYPE, Email.TYPE_HOME); builder.withValue(Email.DATA, email); builder.withValue(Data.IS_PRIMARY, 1); operationList.add(builder.build()); } try { getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList); Toast.makeText(this, R.string.import_to_phone_success, Toast.LENGTH_SHORT).show(); } catch (RemoteException e) { Toast.makeText(this, R.string.import_to_phone_fail, Toast.LENGTH_SHORT).show(); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); } catch (OperationApplicationException e) { Toast.makeText(this, R.string.import_to_phone_fail, Toast.LENGTH_SHORT).show(); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); } } // private void actuallyImportOneSimContact(String name, String phoneNumber) { // final NamePhoneTypePair namePhoneTypePair = // new NamePhoneTypePair(name); // name = namePhoneTypePair.name; // final int phoneType = namePhoneTypePair.phoneType; // final ArrayList<ContentProviderOperation> operationList = // new ArrayList<ContentProviderOperation>(); // ContentProviderOperation.Builder builder = // ContentProviderOperation.newInsert(RawContacts.CONTENT_URI); // builder.withValues(new ContentValues()); // operationList.add(builder.build()); // // builder = ContentProviderOperation.newInsert(Data.CONTENT_URI); // builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0); // builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); // builder.withValue(StructuredName.DISPLAY_NAME, name); // operationList.add(builder.build()); // // builder = ContentProviderOperation.newInsert(Data.CONTENT_URI); // builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0); // builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); // builder.withValue(Phone.TYPE, phoneType); // builder.withValue(Phone.NUMBER, phoneNumber); // builder.withValue(Data.IS_PRIMARY, 1); // operationList.add(builder.build()); // // try { // getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList); // } catch (RemoteException e) { // Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // } catch (OperationApplicationException e) { // Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // } // } //modify by zhengshenglan at 08-24 end private class NamePhoneTypePair { String name; int phoneType; public NamePhoneTypePair(String nameWithPhoneType) { // Look for /W /H /M or /O at the end of the name signifying the type phoneType = Phone.TYPE_OTHER; name = nameWithPhoneType; if(nameWithPhoneType!=null){ int nameLen = nameWithPhoneType.length(); if (nameLen - 2 >= 0 && nameWithPhoneType.charAt(nameLen - 2) == '/') { char c = Character.toUpperCase(nameWithPhoneType.charAt(nameLen - 1)); if (c == 'W') { phoneType = Phone.TYPE_WORK; } else if (c == 'M' || c == 'O') { phoneType = Phone.TYPE_MOBILE; } else if (c == 'H') { phoneType = Phone.TYPE_HOME; } else { phoneType = Phone.TYPE_OTHER; } name = nameWithPhoneType.substring(0, nameLen - 2); } } } } /** * Event handler for the use case where the user starts typing without * bringing up the search UI first. */ public boolean onKey(View v, int keyCode, KeyEvent event) { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0 && !mSearchInitiated) { int unicodeChar = event.getUnicodeChar(); if (unicodeChar != 0) { mSearchInitiated = true; startSearch(new String(new int[]{unicodeChar}, 0, 1), false, null, false); return true; } } return false; } /** * Event handler for search UI. */ public void afterTextChanged(Editable s) { onSearchTextChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } /** * Event handler for search UI. */ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { hideSoftKeyboard(); if (TextUtils.isEmpty(getTextFilter())) { finish(); } return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { if (callSelection()) { return true; } break; } case KeyEvent.KEYCODE_DEL: { if (deleteSelection()) { return true; } break; } } return super.onKeyDown(keyCode, event); } private boolean deleteSelection() { if ((mMode & MODE_MASK_PICKER) != 0) { return false; } final int position = getListView().getSelectedItemPosition(); if (position != ListView.INVALID_POSITION) { Uri contactUri = getContactUri(position); if (contactUri != null) { doContactDelete(contactUri); return true; } } return false; } /** * Prompt the user before deleting the given {@link Contacts} entry. */ protected void doContactDelete(Uri contactUri) { mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); Sources sources = Sources.getInstance(ContactsListActivity.this); Cursor c = getContentResolver().query(RawContacts.CONTENT_URI, RAW_CONTACTS_PROJECTION, RawContacts.CONTACT_ID + "=" + ContentUris.parseId(contactUri), null, null); if (c != null) { try { while (c.moveToNext()) { final String accountType = c.getString(2); final long rawContactId = c.getLong(0); ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } } } finally { c.close(); } } mSelectedContactUri = contactUri; if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt > 0) { showDialog(R.id.dialog_readonly_contact_delete_confirmation); } else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) { showDialog(R.id.dialog_readonly_contact_hide_confirmation); } else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) { showDialog(R.id.dialog_multiple_contact_delete_confirmation); } else { showDialog(R.id.dialog_delete_contact_confirmation); } } /** * Dismisses the soft keyboard when the list takes focus. */ public void onFocusChange(View view, boolean hasFocus) { if (view == getListView() && hasFocus) { hideSoftKeyboard(); } } /** * add by dory.zheng for sim contacts can't edit in favoiters * @param cursor */ private Intent startSimViewContact(Cursor cursor){ Log.v(TAG, "startSimViewContact"); Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setClass(this, SimViewContactActivity.class); intent.putExtra("sim_index", cursor.getString(SUMMARY_SIM_COLUMN_INDEX)); //added for dual sim String accountName = Account.SIM1_ACCOUNT_NAME; int sim_index = cursor.getInt(SUMMARY_SIM_COLUMN_INDEX); Log.v(TAG, "sim_index = " + sim_index); Cursor c = this.getContentResolver().query(Uri.parse("content://"+"com.android.contacts"+"/phone_or_email"), new String[] {StructuredName.DISPLAY_NAME}, RawContacts.SIM_INDEX + "=" + sim_index + " AND " + Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null, null); String tag = ""; try { if(c.moveToFirst()){ tag = c.getString(0); } } catch (Exception e) { Log.w(TAG, "Exception"); e.printStackTrace(); }finally{ if(c != null){ c.close(); c = null; } } intent.putExtra("tag", tag); //yeezone:jinwei use data1 column instead of display name //intent.putExtra("tag", cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX)); ArrayList<String> phoneNum = null ; boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; if (hasPhone) { phoneNum=getAllDataPhoneNum(cursor); } Bundle b = new Bundle(); b.putStringArrayList("numbers", phoneNum); intent.putExtras(b); intent.putExtra("contactid", cursor.getLong(SUMMARY_ID_COLUMN_INDEX)); intent.putExtra("sim_index", ""+sim_index); //added for dual sim if(Config.isMSMS){ accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); Log.i(TAG, "accountName = " + accountName); intent.putExtra("account_name", accountName); } Log.v(TAG, "startSimViewContact, contactid=" + cursor.getLong(SUMMARY_ID_COLUMN_INDEX)+", tag="+tag +", numbers="+phoneNum+", sim_index="+sim_index+", account_name="+accountName); return intent; } private void startSimContactActivity(Cursor cursor, int mode){ Log.v(TAG, "startSimContactActivity"); Intent intent; String accountName = Account.SIM1_ACCOUNT_NAME; if(Config.isMSMS){ if(CommonUtil.isAirplaneMode(this)){ Log.d(TAG, "Air plane mode is on can not access sim contacts"); return; } } if(mode==MODE_VIEW){ // intent=new Intent(Intent.ACTION_VIEW); // intent.setClass(this, SimViewContactActivity.class); intent = new Intent(Intent.ACTION_VIEW, getIntent().getData()); }else { intent=new Intent(Intent.ACTION_EDIT); intent.setClass(this, SimEditContactActivity.class); } //added for dual sim if(Config.isMSMS){ accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); Log.i(TAG,"startSimContactActivity, accountName:"+accountName); intent.putExtra("account_name", accountName); } intent.putExtra("mode", mode); if(mode!=MODE_INSERT){ intent.putExtra("sim_index", cursor.getString(SUMMARY_SIM_COLUMN_INDEX)); //TODO int sim_index = cursor.getInt(SUMMARY_SIM_COLUMN_INDEX); Log.v(TAG, "sim_index = " + sim_index); Cursor c = null; if(Config.isMSMS){ c = this.getContentResolver().query(Uri.parse("content://"+"com.android.contacts"+"/phone_or_email"), new String[] {StructuredName.DISPLAY_NAME}, RawContacts.SIM_INDEX + "=" + sim_index + " AND " + Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "' AND account_name='"+accountName+"'", null, null); } else{ c = this.getContentResolver().query(Uri.parse("content://"+"com.android.contacts"+"/phone_or_email"), new String[] {StructuredName.DISPLAY_NAME}, RawContacts.SIM_INDEX + "=" + sim_index + " AND " + Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null, null); } if(null==c) return; String tag = ""; try { if(c.moveToFirst()){ tag = c.getString(0); } } catch (Exception e) { Log.w(TAG, "Exception"); e.printStackTrace(); }finally{ if(c != null){ c.close(); c = null; } } intent.putExtra("tag", tag); //yeezone:jinwei use data1 column instead of display name //intent.putExtra("tag", cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX)); ArrayList<String> phoneNum = null ; boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; phoneNum = getAllDataPhoneNum(cursor); Bundle b = new Bundle(); b.putStringArrayList("numbers", phoneNum); intent.putExtras(b); intent.putExtra("contactid", cursor.getLong(SUMMARY_ID_COLUMN_INDEX)); intent.putExtra("sim_index", ""+sim_index); Log.v(TAG, "startSimContactActivity, contactid=" + cursor.getLong(SUMMARY_ID_COLUMN_INDEX)+", tag="+tag +", numbers="+phoneNum+", sim_index="+sim_index+", mode="+mode+", account_name="+accountName); } //modify by dory.zheng for NEWMS00136979 begin // if(cursor!=null){ // cursor.close(); // } //modify by dory.zheng for NEWMS00136979 end if(mode == MODE_INSERT){ //yeezone:jinwei 2011-12-15 for insert return previous group startActivityForResult(intent, REQUEST_CODE_FOR_GROUP_ALL); }else{ startActivity(intent); } } /** * Dismisses the soft keyboard when the list takes focus. */ public boolean onTouch(View view, MotionEvent event) { if (view == getListView()) { hideSoftKeyboard(); } return false; } /** * Dismisses the search UI along with the keyboard if the filter text is empty. */ public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (mSearchMode && keyCode == KeyEvent.KEYCODE_BACK && TextUtils.isEmpty(getTextFilter())) { hideSoftKeyboard(); onBackPressed(); return true; } return false; } /** * modify by dory.zheng for huawei call phone can't save to sim begin */ private void displayContactsDialog() { // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Adapter that shows a list of string resources final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final String resString = this.getItem(position); ((TextView)convertView).setText(resString); return convertView; } }; adapter.add(getString(R.string.group_phone)); if(TelephonyManager.SIM_STATE_READY == ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getSimState()){ adapter.add(getString(R.string.group_sim)); } final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // // for group final String resString = adapter.getItem(which); Intent intent = null; if (resString == getString(R.string.group_phone)) { intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); Bundle extras = getIntent().getExtras(); if (extras != null) { intent.putExtras(extras); } intent.putExtra(KEY_PICKER_MODE, (mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER); startActivity(intent); finish(); } else if (resString == getString(R.string.group_sim)) { if(!simCardReady(false)){ return; } int emailNum = 0; String serviceName = "simphonebook"; emailNum = getEmailNumber(serviceName); Log.d(TAG, "SIM_emailNum1 = " + emailNum); intent = new Intent(Intent.ACTION_INSERT); intent.setClass(ContactsListActivity.this, SimEditContactActivity.class); Bundle extras = getIntent().getExtras(); String number = extras.getString(Insert.PHONE); //modify by dory.zheng for call phone can't save contacts to sim card String email = extras.getString(Insert.EMAIL); Bundle b = new Bundle(); b.putInt("mode", SimEditContactActivity.MENU_ITEM_INSERT); // Whether containing the information about Email. if(isEmail) { if(!(emailNum > 0)) { Toast.makeText(dialogContext, R.string.cant_not_save_email, Toast.LENGTH_SHORT).show(); return; } b.putString(SimEditContactActivity.SIM_EMAIL, email); } // number is not null. if(!TextUtils.isEmpty(number)){ b.putString("number", number); } intent.putExtras(b); startActivity(intent); finish(); } } }; new AlertDialog.Builder(this) .setTitle(R.string.select_contacts_group) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(adapter, -1, clickListener) .show(); } /** * add by dory.zheng for contacts is replace * @param contactId * @param number * @return */ private HashMap<String, Object> findPhoneNumbers(long contactId, String number,String serviceName) { HashMap<String, Object> map = new HashMap<String, Object>(); ArrayList<String> mData = new ArrayList<String>(); ArrayList<String> oldData = new ArrayList<String>(); Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); Cursor phonesCursor = getContentResolver().query( dataUri, new String[] { Phone._ID, Phone.NUMBER, Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE, Data.MIMETYPE, Phone.LABEL, Email.DATA, StructuredName.DATA1 }, Data.MIMETYPE + "=? or " + Data.MIMETYPE + "=? or " + Data.MIMETYPE + "=?", new String[] { Phone.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE, StructuredName.CONTENT_ITEM_TYPE }, null); String name = ""; String phoneHome = ""; String phoneMobile = ""; String phoneWork = ""; String phoneOther = ""; String email = ""; String type; int phoneType; while (phonesCursor != null && phonesCursor.moveToNext()) { // Found super primary, call it. type = phonesCursor.getString(phonesCursor.getColumnIndex(Data.MIMETYPE)); if (StructuredName.CONTENT_ITEM_TYPE.equals(type)) { name = phonesCursor.getString(phonesCursor.getColumnIndex(StructuredName.DATA1)); continue; } if (Email.CONTENT_ITEM_TYPE.equals(type)) { email = phonesCursor.getString(phonesCursor.getColumnIndex(Email.DATA)); continue; } if (Phone.CONTENT_ITEM_TYPE.equals(type)) { phoneType = phonesCursor.getInt(phonesCursor.getColumnIndex("data2")); if (phoneType == Phone.TYPE_HOME) { phoneHome = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_MOBILE) { phoneMobile = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_WORK) { phoneWork = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_OTHER) { phoneOther = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); continue; } } } if (phonesCursor != null) { phonesCursor.close(); } oldData.clear(); oldData.add(phoneHome); oldData.add(phoneMobile); oldData.add(phoneWork); oldData.add(phoneOther); oldData.add(email); map.clear(); map.put("oldData", oldData); IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(ServiceManager .getService(serviceName)); int anrNum = 0; try { anrNum = iccIpb.getAnrNum(); } catch (RemoteException ex) { Log.v(TAG, "excetpion"); } catch (SecurityException ex) { Log.v(TAG, "excetpion"); } switch (anrNum) { case 0: if (!phoneHome.equals("")) { Toast.makeText(ContactsListActivity.this, getString(R.string.contacts_information_is_replace), Toast.LENGTH_SHORT).show(); } phoneHome = number; break; case 1: if (phoneHome.equals("")) { phoneHome = number; } else if (phoneMobile.equals("")) { phoneMobile = number; } else { phoneHome = number; Toast.makeText(ContactsListActivity.this, getString(R.string.contacts_information_is_replace), Toast.LENGTH_SHORT).show(); } break; case 2: if (phoneHome.equals("")) { phoneHome = number; } else if (phoneMobile.equals("")) { phoneMobile = number; } else if (phoneWork.equals("")) { phoneWork = number; } else { phoneHome = number; Toast.makeText(ContactsListActivity.this, getString(R.string.contacts_information_is_replace), Toast.LENGTH_SHORT).show(); } break; default: if (phoneHome.equals("")) { phoneHome = number; } else if (phoneMobile.equals("")) { phoneMobile = number; } else if (phoneWork.equals("")) { phoneWork = number; } else if (phoneOther.equals("")) { phoneOther = number; } else { phoneHome = number; Toast.makeText(ContactsListActivity.this, getString(R.string.contacts_information_is_replace), Toast.LENGTH_SHORT).show(); } break; } mData.clear(); mData.add(phoneHome); mData.add(phoneMobile); mData.add(phoneWork); mData.add(phoneOther); mData.add(email); map.put("name", name); map.put("mData", mData); return map; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { hideSoftKeyboard(); Cursor cursor = (Cursor) mAdapter.getItem(position); // if(mMode==MODE_DEFAULT && cursor != null && !"0".equals(cursor.getString(SUMMARY_SIM_COLUMN_INDEX))){ // startSimContactActivity(cursor,MODE_VIEW); // return; // } if (mSearchMode && mAdapter.isSearchAllContactsItemPosition(position)) { doSearch(); } else if (mMode == MODE_INSERT_OR_EDIT_CONTACT || mMode == MODE_QUERY_PICK_TO_EDIT) { //modify by dory.zheng for huawei call phone can't save to sim begin Intent intent = null; Bundle mExtras = getIntent().getExtras(); String mNumber = null; if (null != mExtras) { mNumber = mExtras.getString(Insert.PHONE); } if (position == 0 && !mSearchMode && mMode != MODE_QUERY_PICK_TO_EDIT) { //added for dual sim begin if(Config.isMSMS){ final TelephonyManager telManager = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 0)); final TelephonyManager telManager2 = (TelephonyManager) getSystemService( PhoneFactory.getServiceName(Context.TELEPHONY_SERVICE, 1)); final boolean hasSim1 = (null != telManager) ? telManager.hasIccCard() : false; final boolean hasSim2 = (null != telManager2) ? telManager2.hasIccCard() : false; //if() // if called by email application and the people has email, we need to know if it is the usim //waiting for dual sim interface //dengjing //createSelectAccountDialog(this, mNumber, true).show(); //modify by liaobz Intent newIntent = new Intent(this,GalleryPhoneEditActivity.class); newIntent.putExtra("mode", true); newIntent.putExtra("phone", mNumber); startActivity(newIntent); }//add for dual sim end else { TelephonyManager t = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); final boolean hasSim1 = (null != t) ? t.hasIccCard() : false; // Adding the email to the phone directly. if((!hasSim1) && isEmail) { createTo(0, null, this, mNumber, true); } else { displayContactsDialog(); } } return; // intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); //modify by dory.zheng for huawei call phone can't save to sim end } else { //modify by dory.zheng for contacts is replace begin long sim_index = cursor.getLong(cursor.getColumnIndex("sim_index")); if(sim_index > 0){ intent = new Intent(Intent.ACTION_EDIT); intent.setClass(ContactsListActivity.this, SimEditContactActivity.class); Bundle extras = getIntent().getExtras(); String number = extras.getString(Insert.PHONE); String email = extras.getString(Insert.EMAIL); int emailNum = 0; String serviceName = null; String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); if(Config.isMSMS){ if(Account.SIM1_ACCOUNT_NAME.equals(accountName)){ serviceName = "simphonebook"; } else if(Account.SIM2_ACCOUNT_NAME.equals(accountName)){ serviceName = "simphonebook1"; } else{ //do nothing } }else{ serviceName = "simphonebook"; } emailNum = getEmailNumber(serviceName); Log.d(TAG, "SIM_emailNum12 = " + emailNum); Log.d(TAG, "isEmail = " + isEmail); Bundle b = new Bundle(); if(isEmail) { if(!(emailNum > 0)) { Toast.makeText(ContactsListActivity.this, R.string.cant_not_save_email, Toast.LENGTH_SHORT).show(); return; } b.putString(SimEditContactActivity.SIM_EMAIL, email); } long contactid = cursor.getLong(cursor.getColumnIndex("_id")); HashMap<String, Object> map = findPhoneNumbers(contactid, number,serviceName); String mTag = String.valueOf(map.get("name")); ArrayList<String> mData = (ArrayList<String>) map.get("mData"); ArrayList<String> oldData = (ArrayList<String>) map.get("oldData"); b.putStringArrayList("oldData", oldData); b.putStringArrayList("numbers", mData); intent.putExtras(b); intent.putExtra("mode", MODE_EDIT); intent.putExtra("tag", mTag); intent.putExtra("sim_index", String.valueOf(sim_index)); //added for dual sim if(Config.isMSMS){ Log.i(TAG,"onListItemClick, accountName:"+accountName); intent.putExtra("account_name", accountName); } } else { intent = new Intent(Intent.ACTION_EDIT, getSelectedUri(position)); intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); Bundle extras = getIntent().getExtras(); if (extras != null) { intent.putExtras(extras); } intent .putExtra(KEY_PICKER_MODE, (mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER); } startActivity(intent); finish(); // intent = new Intent(Intent.ACTION_EDIT, getSelectedUri(position)); } // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); // Bundle extras = getIntent().getExtras(); // if (extras != null) { // intent.putExtras(extras); // } // intent.putExtra(KEY_PICKER_MODE, (mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER); // // startActivity(intent); // finish(); //modify by dory.zheng for contacts is replace end } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW && position == 0) { //jun for bugzilla 13723 & 13721 //createSelectAccountDialog(mContext, null, false, SUBACTIVITY_NEW_CONTACT).show(); //Intent newContact = new Intent(Intents.Insert.ACTION, Contacts.CONTENT_URI); //startActivityForResult(newContact, SUBACTIVITY_NEW_CONTACT); //modify by liaobz Intent intent = new Intent(this,GalleryPhoneEditActivity.class); intent.putExtra("mode", true); startActivity(intent); } else if (mMode == MODE_JOIN_CONTACT && id == JOIN_MODE_SHOW_ALL_CONTACTS_ID) { mJoinModeShowAllContacts = false; startQuery(); } else if (id > 0) { final Uri uri = getSelectedUri(position); if ((mMode & MODE_MASK_PICKER) == 0) { //modify by dory.zheng for sim contacts can't edit in favoiters Intent intent; // if(!"0".equals(cursor.getString(SUMMARY_SIM_COLUMN_INDEX))){ // intent = startSimViewContact(cursor); // }else{ intent = new Intent(Intent.ACTION_VIEW, uri); // } // final Intent intent = new Intent(Intent.ACTION_VIEW, uri); StickyTabs.setTab(intent, getIntent()); startActivityForResult(intent, SUBACTIVITY_VIEW_CONTACT); } else if (mMode == MODE_JOIN_CONTACT) { returnPickerResult(null, null, uri, id); } else if (mMode == MODE_QUERY_PICK_TO_VIEW) { // Started with query that should launch to view contact final Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); finish(); } else if (mMode == MODE_PICK_PHONE || mMode == MODE_QUERY_PICK_PHONE) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(PHONE_DISPLAY_NAME_COLUMN_INDEX), uri, id); } else if ((mMode & MODE_MASK_PICKER) != 0) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(getSummaryDisplayNameColumnIndex()), uri, id); } else if (mMode == MODE_PICK_POSTAL || mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_LEGACY_PICK_PHONE) { returnPickerResult(null, null, uri, id); } } else { signalError(); } } private void hideSoftKeyboard() { // Hide soft keyboard, if visible InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mList.getWindowToken(), 0); } /** * @param selectedUri In most cases, this should be a lookup {@link Uri}, possibly * generated through {@link Contacts#getLookupUri(long, String)}. */ private void returnPickerResult(Cursor c, String name, Uri selectedUri, long id) { final Intent intent = new Intent(); //added for dual sim String accountName = ""; Long contactId = Long.valueOf(selectedUri.getLastPathSegment()); if(Config.isMSMS){ if(c != null && c.getColumnIndex(RawContacts.ACCOUNT_NAME)>=0){ accountName = c.getString(c.getColumnIndex(RawContacts.ACCOUNT_NAME)); } else{ Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); c = getContentResolver().query(contactUri, new String[] {RawContacts.ACCOUNT_NAME}, null, null, null); if (c != null && c.moveToFirst()) { accountName = c.getString(0); } } if(Account.SIM1_ACCOUNT_NAME.equals(accountName) ||Account.SIM2_ACCOUNT_NAME.equals(accountName)){ if (mMode == MODE_PICK_PHONE || mMode == MODE_QUERY_PICK_PHONE){ Log.d(TAG, "for voice mail"); } else if ((mMode & MODE_MASK_PICKER) != 0){ Toast.makeText(ContactsListActivity.this, R.string.sim_can_not_pick, Toast.LENGTH_SHORT).show(); finish(); } } } if (mShortcutAction != null) { Intent shortcutIntent; if (Intent.ACTION_VIEW.equals(mShortcutAction)) { // This is a simple shortcut to view a contact. shortcutIntent = new Intent(ContactsContract.QuickContact.ACTION_QUICK_CONTACT); shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); shortcutIntent.setData(selectedUri); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_MODE, ContactsContract.QuickContact.MODE_LARGE); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_EXCLUDE_MIMES, (String[]) null); final Bitmap icon = framePhoto(loadContactPhoto(contactId, null, accountName)); if (icon != null) { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaleToAppIconSize(icon)); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher_shortcut_contact)); } } else { // This is a direct dial or sms shortcut. String number = c.getString(PHONE_NUMBER_COLUMN_INDEX); int type = c.getInt(PHONE_TYPE_COLUMN_INDEX); String scheme; int resid; if (Intent.ACTION_CALL.equals(mShortcutAction)) { scheme = Constants.SCHEME_TEL; resid = R.drawable.badge_action_call; } else { scheme = Constants.SCHEME_SMSTO; resid = R.drawable.badge_action_sms; } // Make the URI a direct tel: URI so that it will always continue to work Uri phoneUri = Uri.fromParts(scheme, number, null); shortcutIntent = new Intent(mShortcutAction, phoneUri); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(selectedUri, type, resid,contactId,accountName)); } shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); intent.addFlags((int) id); setResult(RESULT_OK, intent.setData(selectedUri)); } finish(); } private Bitmap framePhoto(Bitmap photo) { if(null==photo){ Log.i(TAG, "framePhoto, photo is null"); return null; } final Resources r = getResources(); final Drawable frame = r.getDrawable(com.android.internal.R.drawable.quickcontact_badge); final int width = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_width); final int height = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_height); frame.setBounds(0, 0, width, height); final Rect padding = new Rect(); frame.getPadding(padding); final Rect source = new Rect(0, 0, photo.getWidth(), photo.getHeight()); final Rect destination = new Rect(padding.left, padding.top, width - padding.right, height - padding.bottom); final int d = Math.max(width, height); final Bitmap b = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); c.translate((d - width) / 2.0f, (d - height) / 2.0f); frame.draw(c); c.drawBitmap(photo, source, destination, new Paint(Paint.FILTER_BITMAP_FLAG)); return b; } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param lookupUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri selectedUri, int type, int actionResId,long contactId, String accountName) { final Resources r = getResources(); boolean drawPhoneOverlay = true; final float scaleDensity = getResources().getDisplayMetrics().scaledDensity; //add by liguxiang 11-02-11 for NEWMS00135706 begin //Bitmap photo = loadContactPhoto(contactId, null); Bitmap photo = sprdloadContactPhoto(selectedUri, null,contactId, accountName); //add by liguxiang 11-02-11 for NEWMS00135706 end if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phone.TYPE_HOME: overlay = getString(R.string.type_short_home); break; case Phone.TYPE_MOBILE: overlay = getString(R.string.type_short_mobile); break; case Phone.TYPE_WORK: overlay = getString(R.string.type_short_work); break; case Phone.TYPE_PAGER: overlay = getString(R.string.type_short_pager); break; case Phone.TYPE_OTHER: overlay = getString(R.string.type_short_other); break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f * scaleDensity); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2 * scaleDensity, 16 * scaleDensity, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - ((int) (20 * scaleDensity)), -1, iconWidth, ((int) (19 * scaleDensity))); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } private Bitmap scaleToAppIconSize(Bitmap photo) { // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); return icon; } private Bitmap createShortcutBitmap() { return Bitmap.createBitmap(mIconSize, mIconSize, Bitmap.Config.ARGB_8888); } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } private Uri getUriToQuery() { switch(mMode) { case MODE_JOIN_CONTACT: return getJoinSuggestionsUri(null); case MODE_FREQUENT: case MODE_STARRED: return Contacts.CONTENT_URI; case MODE_DEFAULT: case MODE_CUSTOM: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT:{ return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_STREQUENT: { return Contacts.CONTENT_STREQUENT_URI; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return People.CONTENT_URI; } case MODE_PICK_PHONE: { return buildSectionIndexerUri(Phone.CONTENT_URI); } case MODE_LEGACY_PICK_PHONE: { return Phones.CONTENT_URI; } case MODE_PICK_POSTAL: { return buildSectionIndexerUri(StructuredPostal.CONTENT_URI); } case MODE_LEGACY_PICK_POSTAL: { return ContactMethods.CONTENT_URI; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } else if (mQueryMode == QUERY_MODE_TEL) { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return getContactFilterUri(mInitialFilter); } case MODE_QUERY_PICK_PHONE: { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } case MODE_GROUP: { return mGroupUri; } default: { throw new IllegalStateException("Can't generate URI: Unsupported Mode."); } } } /** * Build the {@link Contacts#CONTENT_LOOKUP_URI} for the given * {@link ListView} position, using {@link #mAdapter}. */ private Uri getContactUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final Cursor cursor = (Cursor)mAdapter.getItem(position); if (cursor == null) { return null; } switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { final long personId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); return ContentUris.withAppendedId(People.CONTENT_URI, personId); } default: { // Build and return soft, lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); return Contacts.getLookupUri(contactId, lookupKey); } } } /** * Build the {@link Uri} for the given {@link ListView} position, which can * be used as result when in {@link #MODE_MASK_PICKER} mode. */ private Uri getSelectedUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final long id = mAdapter.getItemId(position); switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return ContentUris.withAppendedId(People.CONTENT_URI, id); } case MODE_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_PHONE: { return ContentUris.withAppendedId(Phones.CONTENT_URI, id); } case MODE_PICK_POSTAL: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_POSTAL: { return ContentUris.withAppendedId(ContactMethods.CONTENT_URI, id); } default: { return getContactUri(position); } } } String[] getProjectionForQuery() { switch(mMode) { case MODE_JOIN_CONTACT: case MODE_STREQUENT: case MODE_FREQUENT: case MODE_STARRED: case MODE_DEFAULT: case MODE_CUSTOM: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_GROUP: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: { return mSearchMode ? CONTACTS_SUMMARY_FILTER_PROJECTION : CONTACTS_SUMMARY_PROJECTION; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return CONTACTS_SUMMARY_FILTER_PROJECTION; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return LEGACY_PEOPLE_PROJECTION ; } case MODE_QUERY_PICK_PHONE: case MODE_PICK_PHONE: { return PHONES_PROJECTION; } case MODE_LEGACY_PICK_PHONE: { return LEGACY_PHONES_PROJECTION; } case MODE_PICK_POSTAL: { return POSTALS_PROJECTION; } case MODE_LEGACY_PICK_POSTAL: { return LEGACY_POSTALS_PROJECTION; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL; } else if (mQueryMode == QUERY_MODE_TEL) { return PHONES_PROJECTION; } break; } } // Default to normal aggregate projection return CONTACTS_SUMMARY_PROJECTION; } private Bitmap loadContactPhoto(long contactId, BitmapFactory.Options options, String accountName) { Cursor cursor = null; Bitmap bm = null; try { Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); Log.i(TAG,"loadContactPhoto, contactId:"+contactId+" contactUri:"+contactUri+" photoUri:"+photoUri); cursor = getContentResolver().query(photoUri, new String[] {Photo.PHOTO}, null, null, null); if (cursor != null && cursor.moveToFirst()) { bm = ContactsUtils.loadContactPhoto(cursor, 0, options); } } finally { if (cursor != null) { cursor.close(); } } if (bm == null) { final int[] fallbacks = { R.drawable.ic_contact_picture, R.drawable.ic_contact_picture_2, R.drawable.ic_contact_picture_3 }; //added for dual sim int[] fallbacksSim; if (Config.isMSMS) { fallbacksSim = new int[1]; if(Account.SIM1_ACCOUNT_NAME.equals(accountName)){ fallbacksSim[0] = R.drawable.ic_contact_picture_sim1; } else if(Account.SIM2_ACCOUNT_NAME.equals(accountName)){ fallbacksSim[0] = R.drawable.ic_contact_picture_sim2; } } else{ fallbacksSim = new int[3]; fallbacksSim[0] = R.drawable.ic_sim_contact_picture; fallbacksSim[1] = R.drawable.ic_sim_contact_picture_2; fallbacksSim[2] = R.drawable.ic_sim_contact_picture_3; } cursor= getSimCursor(contactId); if(cursor!=null){ cursor.close(); bm = BitmapFactory.decodeResource(getResources(), fallbacksSim[new Random().nextInt(fallbacksSim.length)]); }else { bm = BitmapFactory.decodeResource(getResources(), fallbacks[new Random().nextInt(fallbacks.length)]); } } return bm; } //add by liguxiang 11-02-11 for NEWMS00135706 private Bitmap sprdloadContactPhoto(Uri selectedUri, BitmapFactory.Options options,long contactId0, String accountName) { Uri contactUri = null; if (Contacts.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(selectedUri))) { // TODO we should have a "photo" directory under the lookup URI itself contactUri = Contacts.lookupContact(getContentResolver(), selectedUri); } else { Cursor cursor = getContentResolver().query(selectedUri, new String[] { Data.CONTACT_ID }, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { final long contactId = cursor.getLong(0); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); } } finally { if (cursor != null) cursor.close(); } } Cursor cursor = null; Bitmap bm = null; try { Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); Log.i(TAG,"sprdloadContactPhoto, contactId:"+contactId0+" contactUri:"+contactUri+" photoUri:"+photoUri); cursor = getContentResolver().query(photoUri, new String[] {Photo.PHOTO}, null, null, null); if (cursor != null && cursor.moveToFirst()) { bm = ContactsUtils.loadContactPhoto(cursor, 0, options); } } finally { if (cursor != null) { cursor.close(); } } if (bm == null) { final int[] fallbacks = { R.drawable.ic_contact_picture, R.drawable.ic_contact_picture_2, R.drawable.ic_contact_picture_3 }; //added for dual sim int[] fallbacksSim; if (Config.isMSMS) { fallbacksSim = new int[1]; if(Account.SIM1_ACCOUNT_NAME.equals(accountName)){ fallbacksSim[0] = R.drawable.ic_contact_picture_sim1; } else{ fallbacksSim[0] = R.drawable.ic_contact_picture_sim2; } } else{ fallbacksSim = new int[3]; fallbacksSim[0] = R.drawable.ic_sim_contact_picture; fallbacksSim[1] = R.drawable.ic_sim_contact_picture_2; fallbacksSim[2] = R.drawable.ic_sim_contact_picture_3; } cursor= getSimCursor(contactId0); if(cursor!=null){ cursor.close(); bm = BitmapFactory.decodeResource(getResources(), fallbacksSim[new Random().nextInt(fallbacksSim.length)]); }else { bm = BitmapFactory.decodeResource(getResources(), fallbacks[new Random().nextInt(fallbacks.length)]); } } return bm; } //add by liguxiang 11-02-11 for NEWMS00135706 end /** * Return the selection arguments for a default query based on the * {@link #mDisplayOnlyPhones} flag. */ private String getContactSelection() { String selectString=""; if (mDisplayOnlyPhones) { selectString = CLAUSE_ONLY_VISIBLE + " AND " + CLAUSE_ONLY_PHONES; } else { selectString = CLAUSE_ONLY_VISIBLE; } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean displayContactsInPhone = prefs.getBoolean(Prefs.DISPLAY_CONTACTS_PHONE, Prefs.DISPLAY_CONTACTS_PHONE_DEFAULT); if (!displayContactsInPhone) { if(!Config.isMSMS) selectString += " AND " + Constants.NOT_DISPLAY_PHONE_CONTACTS; } //added for dual sim if(Config.isMSMS){ boolean displayContactsInSIM1 = prefs.getBoolean(Prefs.DISPLAY_CONTACTS_SIM1, Prefs.DISPLAY_CONTACTS_SIM1_DEFAULT); boolean displayContactsInSIM2 = prefs.getBoolean(Prefs.DISPLAY_CONTACTS_SIM2, Prefs.DISPLAY_CONTACTS_SIM2_DEFAULT); Log.d(TAG, "[getContactSelection] mDisplayOnlyPhones=" + mDisplayOnlyPhones+", mContactsGroup="+mContactsGroup); Log.d(TAG, "[getContactSelection] displayContactsInSIM1= " + displayContactsInSIM1 + ", displayContactsInSIM2=" + displayContactsInSIM2+", displayContactsInPhone="+displayContactsInPhone); String clauseDisplayAllPhone = " account_name is null"; String clauseDisplaySim1 = " account_name = 'SIM1' "; String clauseDisplaySim2 = " account_name = 'SIM2' "; String andConnection = " AND "; String orConnection = " OR "; //we need to redefine the logic of the filter if(displayContactsInPhone && displayContactsInSIM1 && displayContactsInSIM2){ //display all phone and sim1 and sim2 contacts selectString += andConnection + "( " + clauseDisplayAllPhone + orConnection + clauseDisplaySim1 + orConnection + clauseDisplaySim2 ;// + ")"; }else if(displayContactsInPhone && displayContactsInSIM1){ selectString += andConnection + "( " + clauseDisplayAllPhone + orConnection + clauseDisplaySim1;// + ")"; }else if(displayContactsInPhone && displayContactsInSIM2){ selectString += andConnection + "( " + clauseDisplayAllPhone + orConnection + clauseDisplaySim2; // + ")"; }else if(displayContactsInSIM1 && displayContactsInSIM2){ selectString += andConnection + "( " + clauseDisplaySim1 + orConnection + clauseDisplaySim2;// + ")"; }else if(displayContactsInPhone){ selectString += andConnection + "( " + clauseDisplayAllPhone; }else if(displayContactsInSIM1){ selectString += andConnection + "( " + clauseDisplaySim1; }else if(displayContactsInSIM2){ selectString += andConnection + "( " + clauseDisplaySim2; }else{ selectString += andConnection + "( account_name is not null AND account_name <>'SIM1' AND account_name <> 'SIM2' ";// )"; } //add for other account final ContentResolver resolver = getContentResolver(); final Uri settingsUri = ContactsContract.Settings.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.Settings.UNGROUPED_VISIBLE,"1").build(); final Cursor cursor = resolver.query(settingsUri, new String[] { ContactsContract.Settings.SHOULD_SYNC, ContactsContract.Settings.UNGROUPED_VISIBLE, ContactsContract.Settings.ACCOUNT_NAME, ContactsContract.Settings.ACCOUNT_TYPE }, null, null, null); String otherAccountName = null; String otherAccountType = null; try { if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); do{ otherAccountName = cursor.getString(2); otherAccountType = cursor.getString(3); Log.d(TAG, "accountName from settings is " + otherAccountName + " accountType from settings is "+ otherAccountType); selectString += orConnection + " (account_name is not null and account_type = '" + otherAccountType +"' and account_name = '"+ otherAccountName + "')" ; }while(cursor.moveToNext()); }//if cursor != null selectString += ")"; } finally { if (cursor != null) cursor.close(); } Log.d(TAG, "selectString = " + selectString); } else{ boolean displayContactsInSIM = prefs.getBoolean(Prefs.DISPLAY_CONTACTS_SIM, Prefs.DISPLAY_CONTACTS_SIM_DEFAULT); Log.d(TAG, "[getContactSelection] displayContactsInPhone=" + displayContactsInPhone + ", displayContactsInSIM=" + displayContactsInSIM); if (!displayContactsInSIM && mContactsGroup!=GROUP_SIM) { selectString += " AND " + Constants.NOT_DISPLAY_SIM_CONTACTS; } } if(mContactsGroupNameId != -1){ selectString += " AND divided_group_name_id="+mContactsGroupNameId; String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0 /*|| airPlaneMode*/){ selectString+=" AND sim_index=0"; } return selectString; } if(mContactsGroup==GROUP_PHONE){ selectString+=" AND sim_index=0"; }else if (mContactsGroup==GROUP_SIM) { String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0 /*|| airPlaneMode*/){ Toast.makeText(ContactsListActivity.this, R.string.sim_no_ready, Toast.LENGTH_SHORT).show(); selectString+=" AND sim_index<0"; }else{ if(!getSyncState().equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTED)){ selectString+=" AND sim_index<0"; }else{ selectString+=" AND sim_index<>0"; } } } //added for dual sim else if (mContactsGroup==GROUP_SIM1) { String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0 /*|| airPlaneMode*/){ Toast.makeText(ContactsListActivity.this, R.string.sim1_no_ready, Toast.LENGTH_SHORT).show(); selectString+=" AND sim_index<0"; }else{ selectString+=" AND account_name='"+Account.SIM1_ACCOUNT_NAME+"'"; } }else if (mContactsGroup==GROUP_SIM2) { String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if(sim_oper_num == null || sim_oper_num.length() == 0 /*|| airPlaneMode*/){ Toast.makeText(ContactsListActivity.this, R.string.sim2_no_ready, Toast.LENGTH_SHORT).show(); selectString+=" AND sim_index<0"; }else{ selectString+=" AND account_name='"+Account.SIM2_ACCOUNT_NAME+"'"; } } else if (mContactsGroup == GROUP_ALL) { if (!Config.isMSMS) { Log.d(TAG, "[getContactSelection] GROUP_ALL is not MSMS"); String sim_oper_num = android.os.SystemProperties.get(PROPERTY_ICC_OPERATOR_NUMERIC); if (sim_oper_num == null || sim_oper_num.length() == 0) { Log.d(TAG, "[getContactSelection] GROUP_ALL is not MSMS and sim_oper_num is empty"); selectString += " AND sim_index=0"; } else { if (!getSyncState().equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTED)) { Log.d(TAG, "[getContactSelection] GROUP_ALL is not MSMS and sync state is not sim.state.imported"); // comment this for error that can't load sim contacts // selectString += " AND sim_index=0"; } } } } Log.d(TAG, "9999999999999999selectString = " + selectString); return selectString; } private String getSyncState(){ SharedPreferences pref = getSharedPreferences(SyncSimContactsService.PREFS_SIM_FILE, MODE_PRIVATE); String str = pref.getString(SyncSimContactsService.PREFS_SIM_KEY, SyncSimContactsService.PREFS_SIM_STATE_IDLE); return str; } private boolean isPhoneNumberOnly(String str) { if (!TextUtils.isEmpty(str)) { final int len = str.length(); for (int i = 0; i < len; i++) { char ch = str.charAt(i); if (ch < '0' || ch > '9') { return false; } } return true; } return false; } private Uri getContactAndPhoneFilterUri(String filter) { Uri baseUri = null; if (!TextUtils.isEmpty(filter)) { /* if (isPhoneNumberOnly(filter)) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_URI, "search/" + Uri.encode(filter)); } else { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(filter)); } */ baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(filter)); } else { baseUri = Contacts.CONTENT_URI; } return baseUri; } private Uri getContactFilterUri(String filter) { Uri baseUri; if (!TextUtils.isEmpty(filter)) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); } else { baseUri = Contacts.CONTENT_URI; } if (mAdapter.getDisplaySectionHeadersEnabled()) { return buildSectionIndexerUri(baseUri); } else { return baseUri; } } private Uri getPeopleFilterUri(String filter) { if (!TextUtils.isEmpty(filter)) { return Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(filter)); } else { return People.CONTENT_URI; } } private static Uri buildSectionIndexerUri(Uri uri) { return uri.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); } private Uri getJoinSuggestionsUri(String filter) { Builder builder = Contacts.CONTENT_URI.buildUpon(); builder.appendEncodedPath(String.valueOf(mQueryAggregateId)); builder.appendEncodedPath(AggregationSuggestions.CONTENT_DIRECTORY); if (!TextUtils.isEmpty(filter)) { builder.appendEncodedPath(Uri.encode(filter)); } builder.appendQueryParameter("limit", String.valueOf(MAX_SUGGESTIONS)); return builder.build(); } private String getSortOrder(String[] projectionType) { if(mSortOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY){ return Contacts.SORT_KEY_PRIMARY ; }else{ return Contacts.SORT_KEY_ALTERNATIVE; } } // private static String getSortOrder(String[] projectionType) { /* if (Locale.getDefault().equals(Locale.JAPAN) && projectionType == AGGREGATES_PRIMARY_PHONE_PROJECTION) { return SORT_STRING + " ASC"; } else { return NAME_COLUMN + " COLLATE LOCALIZED ASC"; } */ // return NAME_COLUMN + " COLLATE LOCALIZED ASC"; // } void startQuery() { Log.v(TAG, "startQuery"); if (mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); foundContactsText.setText(R.string.search_results_searching); } mAdapter.setLoading(true); // Cancel any pending queries mQueryHandler.cancelOperation(QUERY_TOKEN); mQueryHandler.setLoadingJoinSuggestions(false); mSortOrder = mContactsPrefs.getSortOrder(); mDisplayOrder = mContactsPrefs.getDisplayOrder(); // When sort order and display order contradict each other, we want to // highlight the part of the name used for sorting. mHighlightWhenScrolling = false; if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_ALTERNATIVE) { mHighlightWhenScrolling = true; } else if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_ALTERNATIVE && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { mHighlightWhenScrolling = true; } String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { mAdapter.changeCursor(new MatrixCursor(projection)); return; } String callingPackage = getCallingPackage(); Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(callingPackage)) { uri = uri.buildUpon() .appendQueryParameter(ContactsContract.REQUESTING_PACKAGE_PARAM_KEY, callingPackage) .build(); } // Kick off the new query switch (mMode) { case MODE_GROUP: case MODE_DEFAULT: case MODE_CUSTOM: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: Log.v(TAG, "mmContactsGroupNameId: " + mContactsGroupNameId + "uri::" + uri.toString()); mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, getContactSelection(), null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, People.DISPLAY_NAME); break; } case MODE_PICK_POSTAL: case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_PHONE: case MODE_QUERY_PICK_TO_VIEW: case MODE_QUERY_PICK_TO_EDIT: { mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, getSortOrder(projection)); break; } case MODE_STARRED: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); break; case MODE_FREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); break; case MODE_STREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; case MODE_PICK_PHONE: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_PHONE: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, Phones.DISPLAY_NAME); break; case MODE_LEGACY_PICK_POSTAL: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, ContactMethods.KIND + "=" + android.provider.Contacts.KIND_POSTAL, null, ContactMethods.DISPLAY_NAME); break; case MODE_JOIN_CONTACT: mQueryHandler.setLoadingJoinSuggestions(true); mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; } } /** * Called from a background thread to do the filter and return the resulting cursor. * * @param filter the text that was entered to filter on * @return a cursor with the results of the filter */ Cursor doFilter(String filter) { String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { return new MatrixCursor(projection); } final ContentResolver resolver = getContentResolver(); switch (mMode) { case MODE_DEFAULT: { Uri uri = getContactAndPhoneFilterUri(filter); return resolver.query(uri, projection, getContactSelection(), null, getSortOrder(projection)); } case MODE_CUSTOM: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: { return resolver.query(getContactFilterUri(filter), projection, getContactSelection(), null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return resolver.query(getPeopleFilterUri(filter), projection, null, null, People.DISPLAY_NAME); } case MODE_STARRED: { return resolver.query(getContactFilterUri(filter), projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); } case MODE_FREQUENT: { return resolver.query(getContactFilterUri(filter), projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); } case MODE_STREQUENT: { Uri uri; if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Contacts.CONTENT_STREQUENT_FILTER_URI, Uri.encode(filter)); } else { uri = Contacts.CONTENT_STREQUENT_URI; } return resolver.query(uri, projection, null, null, null); } case MODE_PICK_PHONE: { Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(filter)); } return resolver.query(uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PHONE: { //TODO: Support filtering here (bug 2092503) break; } case MODE_JOIN_CONTACT: { // We are on a background thread. Run queries one after the other synchronously Cursor cursor = resolver.query(getJoinSuggestionsUri(filter), projection, null, null, null); mAdapter.setSuggestionsCursor(cursor); mJoinModeShowAllContacts = false; return resolver.query(getContactFilterUri(filter), projection, Contacts._ID + " != " + mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } } throw new UnsupportedOperationException("filtering not allowed in mode " + mMode); } private Cursor getShowAllContactsLabelCursor(String[] projection) { MatrixCursor matrixCursor = new MatrixCursor(projection); Object[] row = new Object[projection.length]; // The only columns we care about is the id row[SUMMARY_ID_COLUMN_INDEX] = JOIN_MODE_SHOW_ALL_CONTACTS_ID; matrixCursor.addRow(row); return matrixCursor; } /** * Calls the currently selected list item. * @return true if the call was initiated, false otherwise */ boolean callSelection() { ListView list = getListView(); if (list.hasFocus()) { Cursor cursor = (Cursor) list.getSelectedItem(); return callContact(cursor); } return false; } boolean callContact(Cursor cursor) { return callOrSmsContact(cursor, Action.VOICECALL /*call*/); } boolean videocallContact(Cursor cursor) { return callOrSmsContact(cursor, Action.VIDEOCALL /*call*/); } boolean smsContact(Cursor cursor) { return callOrSmsContact(cursor, Action.SENDSMS /*sms*/); } /** * Calls the contact which the cursor is point to. * @return true if the call was initiated, false otherwise */ boolean callOrSmsContact(Cursor cursor, Action action) { if (cursor == null) { return false; } switch (mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { String phone = cursor.getString(PHONE_NUMBER_COLUMN_INDEX); if (action == Action.SENDSMS) { ContactsUtils.initiateSms(this, phone); } else if (action == Action.VOICECALL) { ContactsUtils.initiateCall(this, phone); } else if (action == Action.VIDEOCALL) { ContactsUtils.initiateVideoCall(this, phone); } return true; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { return false; } default: { boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; if (!hasPhone) { // There is no phone number. signalError(); return false; } String phone = null; Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } //lino modify for huawei KF52678 begin // phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); phonesCursor = queryPhoneNumbersForCall(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); //lino modify for huawei KF52678 end try { if (phonesCursor == null || phonesCursor.getCount() == 0) { // No valid number signalError(); return false; } else if (phonesCursor.getCount() == 1) { // only one number, call it. phonesCursor.moveToFirst();//add this line for CR114540 phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); } else { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { //for sim card IS_SUPER_PRIMARY is always 1 and for bugzilla 13531 if(sim_index.equals("0")){ if (phonesCursor.getInt(phonesCursor. getColumnIndex(Phone.IS_SUPER_PRIMARY)) != 0 ) { // Found super primary, call it. phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); break; } } } } if (phone == null) { // Display dialog to choose a number to call. //TS for compile boolean sendSms = false; if(action == Action.SENDSMS){ sendSms = true; } //PhoneDisambigDialog phoneDialog = new PhoneDisambigDialog( // this, phonesCursor);//NEWMS00114540 PhoneDisambigDialog phoneDialog = new PhoneDisambigDialog(this, phonesCursor, sendSms, 0, action); phoneDialog.show(); } else { if (action == Action.SENDSMS) { ContactsUtils.initiateSms(this, phone); } else if (action == Action.VOICECALL) { ContactsUtils.initiateCall(this, phone); } else if (action == Action.VIDEOCALL) { ContactsUtils.initiateVideoCall(this, phone); } } } catch (Exception e) { e.printStackTrace(); }finally{ if(phonesCursor != null){ phonesCursor.close(); phonesCursor = null; } } } } return true; } //modify by zhengshenglan for NEWMS00118626 at 08-28 begin private ArrayList<Usimphonestruct> getAllExportDataPhoneNum(Cursor cursor, int aiPhoneNumCount, int aiEmailNumCount, int phoneId) { ArrayList<String> usimPhone = new ArrayList<String>(); ArrayList<String> usimEmail = new ArrayList<String>(); Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } String name = queryPhoneName(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); name = getTagNAME(name,phoneId); //added for dual sim if(Config.isMSMS){ String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index, accountName); } else{ phonesCursor = queryPhoneNumbers(cursor .getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); } try { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { String type = phonesCursor.getString(phonesCursor .getColumnIndex(Data.MIMETYPE)); String data = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); if (Phone.CONTENT_ITEM_TYPE.equals(type)) { data = data.replace("-", ""); usimPhone.add(data.length() > 20 ? data.substring(0, 20) : data); } else if (aiEmailNumCount > 0 && Email.CONTENT_ITEM_TYPE.equals(type)) { usimEmail.add(data.length() > 40 ? data.substring(0, 40) : data); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (phonesCursor != null) { phonesCursor.close(); } } int phonenumberpackage = (usimPhone.size() % aiPhoneNumCount == 0 ? usimPhone.size()/aiPhoneNumCount: usimPhone.size()/aiPhoneNumCount+1); phonenumberpackage = phonenumberpackage > usimEmail.size() ? phonenumberpackage : usimEmail.size(); ArrayList<Usimphonestruct> result = new ArrayList<Usimphonestruct>(); for (int i=0; i< phonenumberpackage; i++) { Usimphonestruct usimstruct = new Usimphonestruct(); if (i*aiPhoneNumCount >= usimPhone.size()) { usimstruct.phonenumber = ""; } else { usimstruct.phonenumber = usimPhone.get(i*aiPhoneNumCount); //phonenumber } if (i*aiPhoneNumCount + 1 >= usimPhone.size()) { usimstruct.anr1 = ""; } else { usimstruct.anr1 = usimPhone.get(i*aiPhoneNumCount + 1); //anr1 } if (i*aiPhoneNumCount + 2 >= usimPhone.size()) { usimstruct.anr2 = ""; } else { usimstruct.anr2 = usimPhone.get(i*aiPhoneNumCount + 2); //anr2 } if (i*aiPhoneNumCount + 3 >= usimPhone.size()) { usimstruct.anr3 = ""; } else { usimstruct.anr3 = usimPhone.get(i*aiPhoneNumCount + 3); //anr3 } if (i >= usimEmail.size()) { usimstruct.email = ""; } else { usimstruct.email = usimEmail.get(i); //email } usimstruct.name = name; result.add(usimstruct); } return result; } private ArrayList<String> getAllDataPhoneNum(Cursor cursor) { String phoneHome = ""; String phoneMobile = ""; String phoneWork = ""; String phoneOther = ""; String type; int phoneType; String email = ""; Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } // added for dual sim if (Config.isMSMS) { String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index, accountName); } else { phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); } try { if (phonesCursor == null || phonesCursor.getCount() == 0) { signalError(); } else { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { // Found super primary, call it. type = phonesCursor.getString(phonesCursor.getColumnIndex(Data.MIMETYPE)); if (Email.CONTENT_ITEM_TYPE.equals(type)) { email = phonesCursor.getString(phonesCursor.getColumnIndex(Email.DATA)); continue; } if (Phone.CONTENT_ITEM_TYPE.equals(type)) { phoneType = phonesCursor.getInt(phonesCursor.getColumnIndex("data2")); if (phoneType == Phone.TYPE_HOME) { phoneHome = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_MOBILE) { phoneMobile = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_WORK) { phoneWork = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); continue; } if (phoneType == Phone.TYPE_OTHER) { phoneOther = phonesCursor.getString(phonesCursor .getColumnIndex(Phone.NUMBER)); continue; } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (phonesCursor != null) { phonesCursor.close(); } } Log.v(TAG, "ContactsListActivity---getAllDataPhoneNum---phoneMobile=" + phoneMobile + ";phoneHome=" + phoneHome + ";phoneWork=" + phoneWork + ";phoneOther=" + phoneOther + ";email=" + email); ArrayList<String> phoneOrEmail = new ArrayList<String>(); phoneOrEmail.add(phoneHome); phoneOrEmail.add(phoneMobile); phoneOrEmail.add(phoneWork); phoneOrEmail.add(phoneOther); phoneOrEmail.add(email); return phoneOrEmail; } private String getPhoneNum(Cursor cursor) { String phone = ""; Cursor phonesCursor = null; String sim_index = ""; if (!cursor.isNull(SUMMARY_SIM_COLUMN_INDEX)) { sim_index = cursor.getString(SUMMARY_SIM_COLUMN_INDEX); } phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX), sim_index); try { if (phonesCursor == null || phonesCursor.getCount() == 0) { // No valid number signalError(); } else if (phonesCursor.getCount() == 1) { // only one number, call it. phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); } else { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { Log.d(TAG, "phonesCursor.getInt(phonesCursor.getColumnIndex(Phone.IS_SUPER_PRIMARY)) = " + phonesCursor.getInt(phonesCursor.getColumnIndex(Phone.IS_SUPER_PRIMARY))); if (phonesCursor.getInt(phonesCursor. getColumnIndex(Phone.IS_SUPER_PRIMARY)) != 0) { // Found super primary, call it. phone = phonesCursor. getString(phonesCursor.getColumnIndex(Phone.NUMBER)); Log.d(TAG, "getPhoneNum, phone="+phone); break; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(phonesCursor != null){ phonesCursor.close(); } } if(phone==null){ phone=""; } return phone; } private String queryPhoneName(long contactId, String sim_index) { String name = null; Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); String selection = Data.MIMETYPE + "=?"; if (sim_index != null && !sim_index.equals("")) { selection += " AND " + "sim_index = " + sim_index; } Cursor c = getContentResolver().query(dataUri, new String[] { Phone.NUMBER }, Data.MIMETYPE + "=?", new String[] { StructuredName.CONTENT_ITEM_TYPE }, null); if (c != null && c.moveToNext()) { name = c.getString(c.getColumnIndex(Phone.NUMBER)); } if(c != null){ c.close(); } return name == null ? "" : name; } //lino modify for huawei KF52678 begin private Cursor queryPhoneNumbersForCall(long contactId, String sim_index) { Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); String selection = Data.MIMETYPE + "=?"; if(sim_index != null && !sim_index.equals("")){ selection += " AND " + "sim_index = " + sim_index; } Cursor c = getContentResolver().query(dataUri, new String[] {Phone._ID, Phone.NUMBER, Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE,Data.MIMETYPE, Phone.LABEL}, Data.MIMETYPE + "=?", new String[] {Phone.CONTENT_ITEM_TYPE}, null); return c; } //lino modify for huawei KF52678 end private Cursor queryPhoneNumbers(long contactId, String sim_index) { return queryPhoneNumbers(contactId, sim_index, null); } //added for dual sim private Cursor queryPhoneNumbers(long contactId, String sim_index, String accountName) { Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); String selection = Data.MIMETYPE + "=?"; if(sim_index != null && !sim_index.equals("")){ if(Config.isMSMS){ selection += " AND " + "sim_index = " + sim_index + " AND account_name='"+accountName+"'"; } else{ selection += " AND " + "sim_index = " + sim_index; } } Cursor c = getContentResolver().query(dataUri, new String[] {Phone._ID, Phone.NUMBER, Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE,Data.MIMETYPE, Phone.LABEL,Email.DATA}, Data.MIMETYPE + "=? or "+Data.MIMETYPE + "=?", new String[] {Phone.CONTENT_ITEM_TYPE,Email.CONTENT_ITEM_TYPE}, null); return c; } // TODO: fix PluralRules to handle zero correctly and use Resources.getQuantityText directly protected String getQuantityText(int count, int zeroResourceId, int pluralResourceId) { if (count == 0) { return getString(zeroResourceId); } else { String format = getResources().getQuantityText(pluralResourceId, count).toString(); return String.format(format, count); } } /** * Signal an error to the user. */ void signalError() { //TODO play an error beep or something... } Cursor getItemForView(View view) { ListView listView = getListView(); int index = listView.getPositionForView(view); if (index < 0) { return null; } return (Cursor) listView.getAdapter().getItem(index); } private class QueryHandler extends AsyncQueryHandler { protected final WeakReference<ContactsListActivity> mActivity; protected boolean mLoadingJoinSuggestions = false; public QueryHandler(Context context) { super(context.getContentResolver()); mActivity = new WeakReference<ContactsListActivity>((ContactsListActivity) context); } public void setLoadingJoinSuggestions(boolean flag) { mLoadingJoinSuggestions = flag; } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final ContactsListActivity activity = mActivity.get(); Log.i(TAG,"QueryHandler, onQueryComplete"); if (activity != null && !activity.isFinishing()) { // Whenever we get a suggestions cursor, we need to immediately kick off // another query for the complete list of contacts if (cursor != null && mLoadingJoinSuggestions) { mLoadingJoinSuggestions = false; if (cursor.getCount() > 0) { activity.mAdapter.setSuggestionsCursor(cursor); } else { cursor.close(); activity.mAdapter.setSuggestionsCursor(null); } if (activity.mAdapter.mSuggestionsCursorCount == 0 || !activity.mJoinModeShowAllContacts) { startQuery(QUERY_TOKEN, null, activity.getContactFilterUri( activity.getTextFilter()), CONTACTS_SUMMARY_PROJECTION, Contacts._ID + " != " + activity.mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE + " AND sim_index=0", null, activity.getSortOrder(CONTACTS_SUMMARY_PROJECTION)); mQueryComplete=true; setEmptyText(); return; } cursor = activity.getShowAllContactsLabelCursor(CONTACTS_SUMMARY_PROJECTION); } if(null != cursor && cursor.getCount() > 0){ isEnableDeleteMenu = true; }else{ isEnableDeleteMenu = false; } activity.mAdapter.changeCursor(cursor); // Now that the cursor is populated again, it's possible to restore the list state if (activity.mListState != null) { activity.mList.onRestoreInstanceState(activity.mListState); activity.mListState = null; } } else { if (cursor != null) { cursor.close(); } } mQueryComplete=true; setEmptyText(); } } final static class ContactListItemCache { public CharArrayBuffer nameBuffer = new CharArrayBuffer(128); public CharArrayBuffer dataBuffer = new CharArrayBuffer(128); public CharArrayBuffer highlightedTextBuffer = new CharArrayBuffer(128); public TextWithHighlighting textWithHighlighting; public CharArrayBuffer phoneticNameBuffer = new CharArrayBuffer(128); } final static class PinnedHeaderCache { public TextView titleView; public ColorStateList textColor; public Drawable background; } private final class ContactItemListAdapter extends CursorAdapter implements SectionIndexer, OnScrollListener, PinnedHeaderListView.PinnedHeaderAdapter { private SectionIndexer mIndexer; private boolean mLoading = true; private CharSequence mUnknownNameText; private boolean mDisplayPhotos = false; private boolean mDisplayCallButton = false; private boolean mDisplayAdditionalData = true; private int mFrequentSeparatorPos = ListView.INVALID_POSITION; private boolean mDisplaySectionHeaders = true; private Cursor mSuggestionsCursor; private int mSuggestionsCursorCount; public ContactItemListAdapter(Context context) { super(context, null, false); mUnknownNameText = context.getText(android.R.string.unknownName); switch (mMode) { case MODE_LEGACY_PICK_POSTAL: case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_PHONE: case MODE_PICK_PHONE: case MODE_STREQUENT: case MODE_FREQUENT: mDisplaySectionHeaders = false; break; } if (mSearchMode) { mDisplaySectionHeaders = false; } // Do not display the second line of text if in a specific SEARCH query mode, usually for // matching a specific E-mail or phone number. Any contact details // shown would be identical, and columns might not even be present // in the returned cursor. if (mMode != MODE_QUERY_PICK_PHONE && mQueryMode != QUERY_MODE_NONE) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_NO_DATA) == MODE_MASK_NO_DATA) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_SHOW_CALL_BUTTON) == MODE_MASK_SHOW_CALL_BUTTON) { mDisplayCallButton = true; } if ((mMode & MODE_MASK_SHOW_PHOTOS) == MODE_MASK_SHOW_PHOTOS) { mDisplayPhotos = true; } } public int findFirstPositionForSection(String caption) { int currentSectionItem=-1; ContactsSectionIndexer indexer = (ContactsSectionIndexer) mIndexer; if(indexer == null){ Log.d(TAG, "indexer == null"); return 0; } Object[] sections=indexer.getSections(); for (int i=0;i<sections.length;++i) { String s=(String)sections[i]; if (s.equals(caption)) { currentSectionItem=i; } } if (currentSectionItem==-1) { return 0; } int position=indexer.getPositionForSection(currentSectionItem); Log.d("dengjing", "position = " + position + " currentSectionItem =" + currentSectionItem); return position; } public boolean getDisplaySectionHeadersEnabled() { return mDisplaySectionHeaders; } public void setSuggestionsCursor(Cursor cursor) { if (mSuggestionsCursor != null) { mSuggestionsCursor.close(); } mSuggestionsCursor = cursor; mSuggestionsCursorCount = cursor == null ? 0 : cursor.getCount(); } /** * Callback on the UI thread when the content observer on the backing cursor fires. * Instead of calling requery we need to do an async query so that the requery doesn't * block the UI thread for a long time. */ @Override protected void onContentChanged() { CharSequence constraint = getTextFilter(); if (!TextUtils.isEmpty(constraint)) { // Reset the filter state then start an async filter operation Filter filter = getFilter(); filter.filter(constraint); } else { // Start an async query if (isActivityTop) { startQuery(); } else { isDataChange = true; } } } public void setLoading(boolean loading) { mLoading = loading; } public boolean isFrequentPos(int pos) { return (mFrequentSeparatorPos != ListView.INVALID_POSITION) && (pos > mFrequentSeparatorPos); } @Override public boolean isEmpty() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return true; } if (mSearchMode) { return TextUtils.isEmpty(getTextFilter()); } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW) { // This mode mask adds a header and we always want it to show up, even // if the list is empty, so always claim the list is not empty. return false; } else { if (mCursor == null || mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } } @Override public int getItemViewType(int position) { if (position == 0 && (mShowNumberOfContacts || (mMode & MODE_MASK_CREATE_NEW) != 0)) { return IGNORE_ITEM_VIEW_TYPE; } if (isShowAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (isSearchAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (getSeparatorId(position) != 0) { // We don't want the separator view to be recycled. return IGNORE_ITEM_VIEW_TYPE; } return super.getItemViewType(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } // handle the total contacts item if (position == 0 && mShowNumberOfContacts) { return getTotalContactCountView(parent); } if (position == 0 && (mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact return getLayoutInflater().inflate(R.layout.create_new_contact, parent, false); } if (isShowAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_show_all_item, parent, false); } if (isSearchAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_search_all_item, parent, false); } // Handle the separator specially int separatorId = getSeparatorId(position); if (separatorId != 0) { TextView view = (TextView) getLayoutInflater(). inflate(R.layout.list_separator, parent, false); view.setText(separatorId); return view; } boolean showingSuggestion; Cursor cursor; if (mSuggestionsCursorCount != 0 && position < mSuggestionsCursorCount + 2) { showingSuggestion = true; cursor = mSuggestionsCursor; } else { showingSuggestion = false; cursor = mCursor; } int realPosition = getRealPosition(position); if (!cursor.moveToPosition(realPosition)) { throw new IllegalStateException("couldn't move cursor to position " + position); } boolean newView; View v; if (convertView == null || convertView.getTag() == null) { newView = true; v = newView(mContext, cursor, parent); } else { newView = false; v = convertView; } bindView(v, mContext, cursor); bindSectionHeader(v, realPosition, mDisplaySectionHeaders && !showingSuggestion); return v; } private View getTotalContactCountView(ViewGroup parent) { final LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.total_contacts, parent, false); TextView totalContacts = (TextView) view.findViewById(R.id.totalContactsText); ProgressBar simProgress = (ProgressBar) view.findViewById(R.id.sim_import_progress_title); String text; int count = getRealCount(); if (mSearchMode && !TextUtils.isEmpty(getTextFilter())) { text = getQuantityText(count, R.string.listFoundAllContactsZero, R.plurals.searchFoundContacts); } else { if (mDisplayOnlyPhones) { text = getQuantityText(count, R.string.listTotalPhoneContactsZero, R.plurals.listTotalPhoneContacts); } else { text = getQuantityText(count, R.string.listTotalAllContactsZero, R.plurals.listTotalAllContacts); } } if(getSimImportState() && simCardReady(true)){ text += "(" + getResources().getString(R.string.sim_is_initializing) + ")"; simProgress.setVisibility(View.VISIBLE); }else{ simProgress.setVisibility(View.INVISIBLE); } totalContacts.setText(text); return view; } private boolean getSimImportState(){ SharedPreferences prefState = getSharedPreferences(SyncSimContactsService.PREFS_SIM_FILE, MODE_PRIVATE); String state = prefState.getString(SyncSimContactsService.PREFS_SIM_KEY, SyncSimContactsService.PREFS_SIM_STATE_IDLE); boolean importing = state.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTING); /*boolean booted = SyncSimContactsService.isBootCompleted(); boolean haveImported = false; if(simCardReady()){ haveImported = state.equals(SyncSimContactsService.PREFS_SIM_STATE_IMPORTED); }*/ return importing; //(importing || !booted || !haveImported); } // TODO: fix PluralRules to handle zero correctly and use Resources.getQuantityText directly private String getQuantityText(int count, int zeroResourceId, int pluralResourceId) { if (count == 0) { return getString(zeroResourceId); } else { String format = getResources().getQuantityText(pluralResourceId, count).toString(); return String.format(format, count); } } private boolean isShowAllContactsItemPosition(int position) { return mMode == MODE_JOIN_CONTACT && mJoinModeShowAllContacts && mSuggestionsCursorCount != 0 && position == mSuggestionsCursorCount + 2; } private boolean isSearchAllContactsItemPosition(int position) { return mSearchMode && position == getCount() - 1; } private int getSeparatorId(int position) { int separatorId = 0; if (position == mFrequentSeparatorPos) { separatorId = R.string.favoritesFrquentSeparator; } if (mSuggestionsCursorCount != 0) { if (position == 0) { separatorId = R.string.separatorJoinAggregateSuggestions; } else if (position == mSuggestionsCursorCount + 1) { separatorId = R.string.separatorJoinAggregateAll; } } return separatorId; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final ContactListItemView view = new ContactListItemView(context, null); view.setOnCallButtonClickListener(ContactsListActivity.this); view.setTag(new ContactListItemCache()); return view; } @Override public void bindView(View itemView, Context context, Cursor cursor) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); int typeColumnIndex; int dataColumnIndex; int labelColumnIndex; int defaultType; int nameColumnIndex; int phoneticNameColumnIndex; boolean displayAdditionalData = mDisplayAdditionalData; boolean highlightingEnabled = false; switch(mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { nameColumnIndex = PHONE_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = PHONE_NUMBER_COLUMN_INDEX; typeColumnIndex = PHONE_TYPE_COLUMN_INDEX; labelColumnIndex = PHONE_LABEL_COLUMN_INDEX; defaultType = Phone.TYPE_HOME; break; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { nameColumnIndex = POSTAL_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = POSTAL_ADDRESS_COLUMN_INDEX; typeColumnIndex = POSTAL_TYPE_COLUMN_INDEX; labelColumnIndex = POSTAL_LABEL_COLUMN_INDEX; defaultType = StructuredPostal.TYPE_HOME; break; } default: { nameColumnIndex = getSummaryDisplayNameColumnIndex(); if (mMode == MODE_LEGACY_PICK_PERSON || mMode == MODE_LEGACY_PICK_OR_CREATE_PERSON) { phoneticNameColumnIndex = -1; } else { phoneticNameColumnIndex = SUMMARY_PHONETIC_NAME_COLUMN_INDEX; } dataColumnIndex = -1; typeColumnIndex = -1; labelColumnIndex = -1; defaultType = Phone.TYPE_HOME; displayAdditionalData = false; highlightingEnabled = mHighlightWhenScrolling && mMode != MODE_STREQUENT; } } // Set the name cursor.copyStringToBuffer(nameColumnIndex, cache.nameBuffer); TextView nameView = view.getNameTextView(); //设置字体颜色、大??? nameView.setTextSize(32); nameView.setTextColor(Color.BLACK); int size = cache.nameBuffer.sizeCopied; if (size != 0) { if (highlightingEnabled) { if (cache.textWithHighlighting == null) { cache.textWithHighlighting = mHighlightingAnimation.createTextWithHighlighting(); } buildDisplayNameWithHighlighting(nameView, cursor, cache.nameBuffer, cache.highlightedTextBuffer, cache.textWithHighlighting); } else { nameView.setText(cache.nameBuffer.data, 0, size); } } else { nameView.setText(mUnknownNameText); } boolean hasPhone = cursor.getColumnCount() > SUMMARY_HAS_PHONE_COLUMN_INDEX && cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; // Make the call button visible if requested. if (mDisplayCallButton && hasPhone) { int pos = cursor.getPosition(); view.showCallButton(android.R.id.button1, pos); } else { view.hideCallButton(); } ImageView viewToUse=null; // Set the photo, if requested if (mDisplayPhotos) { boolean useQuickContact = (mMode & MODE_MASK_DISABLE_QUIKCCONTACT) == 0; long photoId = 0; if (!cursor.isNull(SUMMARY_PHOTO_ID_COLUMN_INDEX)) { photoId = cursor.getLong(SUMMARY_PHOTO_ID_COLUMN_INDEX); } if (useQuickContact) { // Build soft lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); QuickContactBadge quickContact = view.getQuickContact(); quickContact.assignContactUri(Contacts.getLookupUri(contactId, lookupKey)); quickContact.setSelectedContactsAppTabIndex(StickyTabs.getTab(getIntent())); viewToUse = quickContact; int sim_index = cursor.getInt(SUMMARY_SIM_COLUMN_INDEX); //modify by dory.zheng for KF48634 begin //if(sim_index != 0){ quickContact.assignContactsSimIndex(sim_index); //} //modify by dory.zheng for KF48634 end } else { viewToUse = view.getPhotoView(); } //联系人头像下方的三点 viewToUse.setBackgroundDrawable(null); viewToUse.setPadding(0, 0, 0, 0); final int position = cursor.getPosition(); mPhotoLoader.loadPhoto(viewToUse, photoId); } if(cursor != null && !cursor.isNull(SUMMARY_SIM_COLUMN_INDEX) && cursor.getInt(SUMMARY_SIM_COLUMN_INDEX)!=0 && viewToUse!=null){ //added for dual sim if(Config.isMSMS){ String accountName = cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_NAME)); Log.i(TAG, "bindView, accountName = " + accountName); if(Account.SIM1_ACCOUNT_NAME.equals(accountName)){ viewToUse.setImageResource(R.drawable.ic_contact_picture_sim1); } else{ viewToUse.setImageResource(R.drawable.ic_contact_picture_sim2); } } else{ viewToUse.setImageResource(R.drawable.ic_sim_contact_list_picture); } }else { if ((mMode & MODE_MASK_NO_PRESENCE) == 0) { // Set the proper icon (star or presence or nothing) int serverStatus; if (!cursor.isNull(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX)) { serverStatus = cursor.getInt(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX); Drawable icon = ContactPresenceIconUtil.getPresenceIcon(mContext, serverStatus); if (icon != null) { view.setPresence(icon); } else { view.setPresence(null); } } else { view.setPresence(null); } } else { view.setPresence(null); } } if (mShowSearchSnippets) { boolean showSnippet = false; String snippetMimeType = cursor.getString(SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX); if (Email.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String email = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(email)) { view.setSnippet(email); showSnippet = true; } } else if (Organization.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String company = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); String title = cursor.getString(SUMMARY_SNIPPET_DATA4_COLUMN_INDEX); if (!TextUtils.isEmpty(company)) { if (!TextUtils.isEmpty(title)) { view.setSnippet(company + " / " + title); } else { view.setSnippet(company); } showSnippet = true; } else if (!TextUtils.isEmpty(title)) { view.setSnippet(title); showSnippet = true; } } else if (Nickname.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String nickname = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(nickname)) { view.setSnippet(nickname); showSnippet = true; } } if (!showSnippet) { view.setSnippet(null); } } if (!displayAdditionalData) { if (phoneticNameColumnIndex != -1) { // Set the name cursor.copyStringToBuffer(phoneticNameColumnIndex, cache.phoneticNameBuffer); int phoneticNameSize = cache.phoneticNameBuffer.sizeCopied; if (phoneticNameSize != 0) { view.setLabel(cache.phoneticNameBuffer.data, phoneticNameSize); } else { view.setLabel(null); } } else { view.setLabel(null); } return; } // Set the data. cursor.copyStringToBuffer(dataColumnIndex, cache.dataBuffer); size = cache.dataBuffer.sizeCopied; view.setData(cache.dataBuffer.data, size); // Set the label. if (!cursor.isNull(typeColumnIndex)) { final int type = cursor.getInt(typeColumnIndex); final String label = cursor.getString(labelColumnIndex); if (mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_PICK_POSTAL) { // TODO cache view.setLabel(StructuredPostal.getTypeLabel(context.getResources(), type, label)); } else { // TODO cache view.setLabel(Phone.getTypeLabel(context.getResources(), type, label)); } } else { view.setLabel(null); } } /** * Computes the span of the display name that has highlighted parts and configures * the display name text view accordingly. */ private void buildDisplayNameWithHighlighting(TextView textView, Cursor cursor, CharArrayBuffer buffer1, CharArrayBuffer buffer2, TextWithHighlighting textWithHighlighting) { int oppositeDisplayOrderColumnIndex; if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } else { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } cursor.copyStringToBuffer(oppositeDisplayOrderColumnIndex, buffer2); textWithHighlighting.setText(buffer1, buffer2); textView.setText(textWithHighlighting); } private void bindSectionHeader(View itemView, int position, boolean displaySectionHeaders) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); if (!displaySectionHeaders) { view.setSectionHeader(null); view.setDividerVisible(true); } else { final int section = getSectionForPosition(position); if (getPositionForSection(section) == position) { String title = (String)mIndexer.getSections()[section]; view.setSectionHeader(title); } else { view.setDividerVisible(false); view.setSectionHeader(null); } // move the divider for the last item in a section if (getPositionForSection(section + 1) - 1 == position) { view.setDividerVisible(false); } else { view.setDividerVisible(true); } } } @Override public void changeCursor(Cursor cursor) { if (cursor != null) { setLoading(false); } mPhotoLoader.clear(); // Get the split between starred and frequent items, if the mode is strequent mFrequentSeparatorPos = ListView.INVALID_POSITION; int cursorCount = 0; if (cursor != null && (cursorCount = cursor.getCount()) > 0 && mMode == MODE_STREQUENT) { cursor.move(-1); for (int i = 0; cursor.moveToNext(); i++) { int starred = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starred == 0) { if (i >= 0) { // Only add the separator when there are starred items present mFrequentSeparatorPos = i; } break; } } } if (cursor != null && mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); String text = getQuantityText(cursor.getCount(), R.string.listFoundAllContactsZero, R.plurals.listFoundAllContacts); foundContactsText.setText(text); } super.changeCursor(cursor); // Update the indexer for the fast scroll widget updateIndexer(cursor); } private void updateIndexer(Cursor cursor) { if (cursor == null) { mIndexer = null; return; } Bundle bundle = cursor.getExtras(); if (bundle.containsKey(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES)) { String sections[] = bundle.getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); int counts[] = bundle.getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); mIndexer = new ContactsSectionIndexer(sections, counts); } else { mIndexer = null; } } /** * Run the query on a helper thread. Beware that this code does not run * on the main UI thread! */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { return doFilter(constraint.toString()); } public Object [] getSections() { if (mIndexer == null) { return new String[] { " " }; } else { return mIndexer.getSections(); } } public int getPositionForSection(int sectionIndex) { if (mIndexer == null) { return -1; } return mIndexer.getPositionForSection(sectionIndex); } public int getSectionForPosition(int position) { if (mIndexer == null) { return -1; } return mIndexer.getSectionForPosition(position); } @Override public boolean areAllItemsEnabled() { return mMode != MODE_STARRED && !mShowNumberOfContacts && mSuggestionsCursorCount == 0; } @Override public boolean isEnabled(int position) { if (mShowNumberOfContacts) { if (position == 0) { return false; } position--; } if (mSuggestionsCursorCount > 0) { return position != 0 && position != mSuggestionsCursorCount + 1; } return position != mFrequentSeparatorPos; } @Override public int getCount() { if (!mDataValid) { return 0; } int superCount = super.getCount(); if (mShowNumberOfContacts && (mSearchMode || superCount > 0)) { // We don't want to count this header if it's the only thing visible, so that // the empty text will display. superCount++; } if (mSearchMode) { // Last element in the list is the "Find superCount++; } // We do not show the "Create New" button in Search mode if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { // Count the "Create new contact" line superCount++; } if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" headers. return mSuggestionsCursorCount + superCount + 2; } else if (mFrequentSeparatorPos != ListView.INVALID_POSITION) { // When showing strequent list, we have an additional list item - the separator. return superCount + 1; } else { return superCount; } } /** * Gets the actual count of contacts and excludes all the headers. */ public int getRealCount() { return super.getCount(); } private int getRealPosition(int pos) { if (mShowNumberOfContacts) { pos--; } if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { return pos - 1; } else if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" separators. if (pos < mSuggestionsCursorCount + 2) { // We are in the upper partition (Suggestions). Adjusting for the "Suggestions" // separator. return pos - 1; } else { // We are in the lower partition (All contacts). Adjusting for the size // of the upper partition plus the two separators. return pos - mSuggestionsCursorCount - 2; } } else if (mFrequentSeparatorPos == ListView.INVALID_POSITION) { // No separator, identity map return pos; } else if (pos <= mFrequentSeparatorPos) { // Before or at the separator, identity map return pos; } else { // After the separator, remove 1 from the pos to get the real underlying pos return pos - 1; } } @Override public Object getItem(int pos) { if (mSuggestionsCursorCount != 0 && pos <= mSuggestionsCursorCount) { mSuggestionsCursor.moveToPosition(getRealPosition(pos)); return mSuggestionsCursor; } else if (isSearchAllContactsItemPosition(pos)){ return null; } else { int realPosition = getRealPosition(pos); if (realPosition < 0) { return null; } return super.getItem(realPosition); } } @Override public long getItemId(int pos) { if (mSuggestionsCursorCount != 0 && pos < mSuggestionsCursorCount + 2) { if (mSuggestionsCursor.moveToPosition(pos - 1)) { return mSuggestionsCursor.getLong(mRowIDColumn); } else { return 0; } } else if (isSearchAllContactsItemPosition(pos)) { return 0; } int realPosition = getRealPosition(pos); if (realPosition < 0) { return 0; } return super.getItemId(realPosition); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (view instanceof PinnedHeaderListView) { ((PinnedHeaderListView)view).configureHeaderView(firstVisibleItem); } } public void onScrollStateChanged(AbsListView view, int scrollState) { if (mHighlightWhenScrolling) { if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) { mHighlightingAnimation.startHighlighting(); } else { mHighlightingAnimation.stopHighlighting(); } } if (scrollState == OnScrollListener.SCROLL_STATE_FLING) { mPhotoLoader.pause(); } else if (mDisplayPhotos) { mPhotoLoader.resume(); } } /** * Computes the state of the pinned header. It can be invisible, fully * visible or partially pushed up out of the view. */ public int getPinnedHeaderState(int position) { if (mIndexer == null || mCursor == null || mCursor.getCount() == 0) { return PINNED_HEADER_GONE; } int realPosition = getRealPosition(position); if (realPosition < 0) { return PINNED_HEADER_GONE; } // The header should get pushed up if the top item shown // is the last item in a section for a particular letter. int section = getSectionForPosition(realPosition); int nextSectionPosition = getPositionForSection(section + 1); if (nextSectionPosition != -1 && realPosition == nextSectionPosition - 1) { return PINNED_HEADER_PUSHED_UP; } return PINNED_HEADER_VISIBLE; } /** * Configures the pinned header by setting the appropriate text label * and also adjusting color if necessary. The color needs to be * adjusted when the pinned header is being pushed up from the view. */ public void configurePinnedHeader(View header, int position, int alpha) { PinnedHeaderCache cache = (PinnedHeaderCache)header.getTag(); if (cache == null) { cache = new PinnedHeaderCache(); cache.titleView = (TextView)header.findViewById(R.id.header_text); cache.textColor = cache.titleView.getTextColors(); cache.background = header.getBackground(); header.setTag(cache); } int realPosition = getRealPosition(position); int section = getSectionForPosition(realPosition); String title = (String)mIndexer.getSections()[section]; cache.titleView.setText(title); if (alpha == 255) { // Opaque: use the default background, and the original text color header.setBackgroundDrawable(cache.background); cache.titleView.setTextColor(cache.textColor); } else { // Faded: use a solid color approximation of the background, and // a translucent text color header.setBackgroundColor(Color.rgb( Color.red(mPinnedHeaderBackgroundColor) * alpha / 255, Color.green(mPinnedHeaderBackgroundColor) * alpha / 255, Color.blue(mPinnedHeaderBackgroundColor) * alpha / 255)); int textColor = cache.textColor.getDefaultColor(); cache.titleView.setTextColor(Color.argb(alpha, Color.red(textColor), Color.green(textColor), Color.blue(textColor))); } } } public final int[] NUMBERTYPE = {Phone.TYPE_MOBILE,Phone.TYPE_WORK,Phone.TYPE_OTHER};// add by zhengshenglan at 08-24 class Usimphonestruct { String name; String phonenumber; String anr1; String anr2; String anr3; String email; } private ContactsPreferences.ChangeListener mPreferencesChangeListener = new ContactsPreferences.ChangeListener() { @Override public void onChange() { // When returning from DisplayOptions, onActivityResult ensures that we reload the list, // so we do not have to do anything here. However, ContactsPreferences requires a change // listener, otherwise it would not reload its settings. } }; private void configureBladeView(final ListView list) { boolean hasBladeView=true; if (list!=null) { BladeView bladeView=(BladeView)findViewById(R.id.blade); if (bladeView==null) { return; } if (!hasBladeView) { bladeView.setVisibility(View.GONE); return; } bladeView.setVisibility(View.VISIBLE); bladeView.setOnItemClickListener(new BladeView.OnItemClickListener() { public void onItemClick(int item) { String currentSection=""; if (item==0) { currentSection=""; } else { currentSection=Character.toString((char)('A'+item-1)); } int position=mAdapter.findFirstPositionForSection(currentSection); list.setSelectionFromTop(position,0); } }); } } }