public class CallBlocker extends BroadcastReceiver {
private static final String TAG = "CallBlocker";
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (!isContact(phoneNumber)) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
telephonyManager.endCall();
}
}
}
private boolean isContact(String phoneNumber) {
ContentResolver contentResolver = mContext.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = contentResolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
cursor.close();
Log.d(TAG, "Incoming call from contact: " + contactName);
return true;
}
cursor.close();
}
Log.d(TAG, "Incoming call from unknown number: " + phoneNumber);
return false;
}
}