1 /* 2 * Copyright (C) 2013 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 17 package com.android.dialer.interactions; 18 19 import android.content.BroadcastReceiver; 20 import android.content.ContentValues; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.database.Cursor; 24 import android.net.Uri; 25 import android.provider.ContactsContract.PhoneLookup; 26 import android.provider.ContactsContract.PinnedPositions; 27 import android.text.TextUtils; 28 29 /** 30 * This broadcast receiver is used to listen to outgoing calls and undemote formerly demoted 31 * contacts if a phone call is made to a phone number belonging to that contact. 32 */ 33 public class UndemoteOutgoingCallReceiver extends BroadcastReceiver { 34 35 private static final long NO_CONTACT_FOUND = -1; 36 37 @Override 38 public void onReceive(final Context context, Intent intent) { 39 if (intent != null && Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) { 40 final String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); 41 if (TextUtils.isEmpty(number)) { 42 return; 43 } 44 final Thread thread = new Thread() { 45 @Override 46 public void run() { 47 final long id = getContactIdFromPhoneNumber(context, number); 48 if (id != NO_CONTACT_FOUND) { 49 undemoteContactWithId(context, id); 50 } 51 } 52 }; 53 thread.start(); 54 } 55 } 56 57 private void undemoteContactWithId(Context context, long id) { 58 final ContentValues cv = new ContentValues(1); 59 cv.put(String.valueOf(id), PinnedPositions.UNDEMOTE); 60 // If the contact is not demoted, this will not do anything. Otherwise, it will 61 // restore it to an unpinned position. If it was a frequently called contact, it will 62 // show up once again show up on the favorites screen. 63 context.getContentResolver().update(PinnedPositions.UPDATE_URI, cv, null, null); 64 } 65 66 private long getContactIdFromPhoneNumber(Context context, String number) { 67 final Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, 68 Uri.encode(number)); 69 final Cursor cursor = context.getContentResolver().query(contactUri, new String[] { 70 PhoneLookup._ID}, null, null, null); 71 if (cursor == null) { 72 return NO_CONTACT_FOUND; 73 } 74 try { 75 if (cursor.moveToFirst()) { 76 final long id = cursor.getLong(0); 77 return id; 78 } else { 79 return NO_CONTACT_FOUND; 80 } 81 } finally { 82 cursor.close(); 83 } 84 } 85 } 86