1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.contacts.interactions; 17 18 import android.content.AsyncTaskLoader; 19 import android.content.ContentValues; 20 import android.content.Context; 21 import android.content.pm.PackageManager; 22 import android.database.Cursor; 23 import android.database.DatabaseUtils; 24 import android.net.Uri; 25 import android.provider.CallLog.Calls; 26 import android.text.TextUtils; 27 import android.util.Log; 28 29 import com.android.contacts.compat.PhoneNumberUtilsCompat; 30 import com.android.contacts.util.PermissionsUtil; 31 32 import com.google.common.annotations.VisibleForTesting; 33 34 import java.util.ArrayList; 35 import java.util.Collections; 36 import java.util.Comparator; 37 import java.util.List; 38 39 public class CallLogInteractionsLoader extends AsyncTaskLoader<List<ContactInteraction>> { 40 41 private static final String TAG = "CallLogInteractions"; 42 43 private final String[] mPhoneNumbers; 44 private final String[] mSipNumbers; 45 private final int mMaxToRetrieve; 46 private List<ContactInteraction> mData; 47 48 public CallLogInteractionsLoader(Context context, String[] phoneNumbers, String[] sipNumbers, 49 int maxToRetrieve) { 50 super(context); 51 mPhoneNumbers = phoneNumbers; 52 mSipNumbers = sipNumbers; 53 mMaxToRetrieve = maxToRetrieve; 54 } 55 56 @Override 57 public List<ContactInteraction> loadInBackground() { 58 final boolean hasPhoneNumber = mPhoneNumbers != null && mPhoneNumbers.length > 0; 59 final boolean hasSipNumber = mSipNumbers != null && mSipNumbers.length > 0; 60 if (!PermissionsUtil.hasPhonePermissions(getContext()) 61 || !getContext().getPackageManager() 62 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY) 63 || (!hasPhoneNumber && !hasSipNumber) || mMaxToRetrieve <= 0) { 64 return Collections.emptyList(); 65 } 66 67 final List<ContactInteraction> interactions = new ArrayList<>(); 68 if (hasPhoneNumber) { 69 for (String number : mPhoneNumbers) { 70 final String normalizedNumber = PhoneNumberUtilsCompat.normalizeNumber(number); 71 if (!TextUtils.isEmpty(normalizedNumber)) { 72 interactions.addAll(getCallLogInteractions(normalizedNumber)); 73 } 74 } 75 } 76 if (hasSipNumber) { 77 for (String number : mSipNumbers) { 78 interactions.addAll(getCallLogInteractions(number)); 79 } 80 } 81 82 // Sort the call log interactions by date for duplicate removal 83 Collections.sort(interactions, new Comparator<ContactInteraction>() { 84 @Override 85 public int compare(ContactInteraction i1, ContactInteraction i2) { 86 if (i2.getInteractionDate() - i1.getInteractionDate() > 0) { 87 return 1; 88 } else if (i2.getInteractionDate() == i1.getInteractionDate()) { 89 return 0; 90 } else { 91 return -1; 92 } 93 } 94 }); 95 // Duplicates only occur because of fuzzy matching. No need to dedupe a single number. 96 if ((hasPhoneNumber && mPhoneNumbers.length == 1 && !hasSipNumber) 97 || (hasSipNumber && mSipNumbers.length == 1 && !hasPhoneNumber)) { 98 return interactions; 99 } 100 return pruneDuplicateCallLogInteractions(interactions, mMaxToRetrieve); 101 } 102 103 /** 104 * Two different phone numbers can match the same call log entry (since phone number 105 * matching is inexact). Therefore, we need to remove duplicates. In a reasonable call log, 106 * every entry should have a distinct date. Therefore, we can assume duplicate entries are 107 * adjacent entries. 108 * @param interactions The interaction list potentially containing duplicates 109 * @return The list with duplicates removed 110 */ 111 @VisibleForTesting 112 static List<ContactInteraction> pruneDuplicateCallLogInteractions( 113 List<ContactInteraction> interactions, int maxToRetrieve) { 114 final List<ContactInteraction> subsetInteractions = new ArrayList<>(); 115 for (int i = 0; i < interactions.size(); i++) { 116 if (i >= 1 && interactions.get(i).getInteractionDate() == 117 interactions.get(i-1).getInteractionDate()) { 118 continue; 119 } 120 subsetInteractions.add(interactions.get(i)); 121 if (subsetInteractions.size() >= maxToRetrieve) { 122 break; 123 } 124 } 125 return subsetInteractions; 126 } 127 128 private List<ContactInteraction> getCallLogInteractions(String phoneNumber) { 129 final Uri uri = Uri.withAppendedPath(Calls.CONTENT_FILTER_URI, 130 Uri.encode(phoneNumber)); 131 // Append the LIMIT clause onto the ORDER BY clause. This won't cause crashes as long 132 // as we don't also set the {@link android.provider.CallLog.Calls.LIMIT_PARAM_KEY} that 133 // becomes available in KK. 134 final String orderByAndLimit = Calls.DATE + " DESC LIMIT " + mMaxToRetrieve; 135 Cursor cursor = null; 136 try { 137 cursor = getContext().getContentResolver().query(uri, null, null, null, 138 orderByAndLimit); 139 } catch (Exception e) { 140 Log.e(TAG, "Can not query calllog", e); 141 } 142 try { 143 if (cursor == null || cursor.getCount() < 1) { 144 return Collections.emptyList(); 145 } 146 cursor.moveToPosition(-1); 147 List<ContactInteraction> interactions = new ArrayList<>(); 148 while (cursor.moveToNext()) { 149 final ContentValues values = new ContentValues(); 150 DatabaseUtils.cursorRowToContentValues(cursor, values); 151 interactions.add(new CallLogInteraction(values)); 152 } 153 return interactions; 154 } finally { 155 if (cursor != null) { 156 cursor.close(); 157 } 158 } 159 } 160 161 @Override 162 protected void onStartLoading() { 163 super.onStartLoading(); 164 165 if (mData != null) { 166 deliverResult(mData); 167 } 168 169 if (takeContentChanged() || mData == null) { 170 forceLoad(); 171 } 172 } 173 174 @Override 175 protected void onStopLoading() { 176 // Attempt to cancel the current load task if possible. 177 cancelLoad(); 178 } 179 180 @Override 181 public void deliverResult(List<ContactInteraction> data) { 182 mData = data; 183 if (isStarted()) { 184 super.deliverResult(data); 185 } 186 } 187 188 @Override 189 protected void onReset() { 190 super.onReset(); 191 192 // Ensure the loader is stopped 193 onStopLoading(); 194 if (mData != null) { 195 mData.clear(); 196 } 197 } 198 }