Search code examples
androidpush-notificationbroadcastreceivertitle

Contact name not showing in Notifications when Sms receives


I am making an app in which when a new SMS receives from known number i.e. if the number is saved in contact list then push notification show. Now the problem is that the notification is not showing display name of contact. It can show message number and message content but not showing display name for that contact.

My code to check if new SMS comes from contact saved is:

public boolean contactExists(Context context, String number) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, 
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
   if (cur.moveToFirst()) {
      return true;
   }
} 
finally 
{
    if (cur != null)
   cur.close();
}
return false;
}

and code for notification alert is:

if (contactExists(context, msg_from))
        {

            NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
            notify.setSmallIcon(R.drawable.appicon);
            notify.setContentTitle(msg_from);
            notify.setContentText(msgBody);
            notify.setAutoCancel(true);
            notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notify.setLights(Color.GREEN, 2000, 2000);
            notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.setType("vnd.android-dir/mms-sms");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
            notify.setContentIntent(intentt);
            //notify.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 268435456));
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notify.build());

        }

now as you see in this line i write "msg_from"

notify.setContentTitle(msg_from);

this will give me the number from where message come from but if i write this:

notify.setContentTitle(PhoneLookup.DISPLAY_NAME);

or other solutions that i found on internet then the notification title displayed will show this string "display_name" and not showing actual name Please Help!

Here is my all code for that class

public class TodoRe extends BroadcastReceiver {
Context context;

ArrayList<String> keywordslist = new ArrayList<String>();


@SuppressLint({ "DefaultLocale", "InlinedApi" })
@Override
public void onReceive(Context context, Intent intent) {

LinkedHashMap<String, String> contactNumber = new LinkedHashMap<String, String>();
DBkeyword screenedKeywordDB = new DBkeyword(context);
SQLiteDatabase db = screenedKeywordDB.getWritableDatabase();
Cursor cur1 = db.rawQuery(Constants.readScreenedKeywords, null);
cur1.moveToFirst();
while (!cur1.isAfterLast()) 
{
    keywordslist.add(cur1.getString(0));
    cur1.moveToNext();
}

db.close();
DBTable dbtable = new DBTable(context);
SQLiteDatabase dbrsn = dbtable.getReadableDatabase();
Cursor cur = dbrsn.rawQuery(Constants.readScreenedNumbers, null);
cur.moveToFirst();

while (!cur.isAfterLast()) 
{
  contactNumber.put(cur.getString(0), cur.getString(1));
  cur.moveToNext();
}
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
  Bundle bundle = intent.getExtras();
  SmsMessage[] msgs = null;
  String msg_from,msgSenderName;
  if (bundle != null) {
    try {
      boolean keywordPresent = false;
      Object[] pdus = (Object[]) bundle.get("pdus");
      msgs = new SmsMessage[pdus.length];
      for (int i = 0; i < msgs.length; i++) {
        msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        msg_from = msgs[i].getOriginatingAddress();

        String msgBody = msgs[i].getMessageBody();
        String title= cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
        msg_from = Utilities.extractNumbers(msg_from);
        Long dateLong = msgs[i].getTimestampMillis();
        String msgDate = dateLong.toString();

        ContentValues values = new ContentValues(); 
        values.put("address", msg_from); 
        values.put("date", System.currentTimeMillis()+""); 
        values.put("read", "1"); 
        values.put("type", "1"); 
        values.put("body",msgBody); 
        Uri uri = Uri.parse("content://sms/"); 
        context.getContentResolver().insert(uri,values);

        if (contactExists(context, msg_from))
        {
            NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
            notify.setSmallIcon(R.drawable.appicon);
            notify.setContentTitle(title);
            notify.setContentText(msgBody);
            notify.setAutoCancel(true);
            notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notify.setLights(Color.GREEN, 2000, 2000);
              notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.setType("vnd.android-dir/mms-sms");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
            notify.setContentIntent(intentt);
            //notify.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 268435456));
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notify.build());

        }


public boolean contactExists(Context context, String number) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, 
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
   if (cur.moveToFirst()) {
      return true;
   }
} 
finally 
{
    if (cur != null)
   cur.close();
}
return false;
}

Here is the code now updated one

ContentValues values = new ContentValues(); 
        values.put("address", msg_from); 
        values.put("date", System.currentTimeMillis()+""); 
        values.put("read", "1"); 
        values.put("type", "1"); 
        values.put("body",msgBody); 
        Uri uri = Uri.parse("content://sms/"); 
        context.getContentResolver().insert(uri,values);
        String title = contactName(context, msg_from);
        String sss=cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
        if (contactExists(context, msg_from) && title != null)
        {
            NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
            notify.setSmallIcon(R.drawable.appicon);
            notify.setContentTitle(sss);
            notify.setContentText(msgBody);
            notify.setAutoCancel(true);
            notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notify.setLights(Color.GREEN, 2000, 2000);
            notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.setType("vnd.android-dir/mms-sms");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
            notify.setContentIntent(intentt);
            //notify.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 268435456));
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notify.build());

        }

public boolean contactExists(Context context, String number) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, 
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
   if (cur.moveToFirst()) {
      return true;
   }
} 
finally 
{
    if (cur != null)
   cur.close();
}
return false;
}

public String contactName(Context context, String number) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, 
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
   if (cur.moveToFirst()) {
       return cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME ));
   }
} 
finally 
{
    if (cur != null)
   cur.close();
}
return null;
}

Now there are two methods,one to check if exist or not and other to return name


Solution

  • The DISPLAY_NAME constant is the name of the database's table column that holds the contact's display name. It's value is "display_name", which is why you're seeing that in the Notification.

    You want the value that the Cursor has for that column. That is, you want:

    cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME))
    

    Change the contactExists() method to return a String for the display name, instead of a boolean that just indicates whether it exists.

    public String contactExists(Context context, String number) {
        ...
    
        try {
            if (cur.moveToFirst()) {
                return cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME ));
            }
        } 
        finally {
            if (cur != null)
                cur.close();
        }
        return null;
    }
    

    Then, change title to be the return from that method, and change the if statement to check if title is not null.

    String title = contactExists(context, msg_from);
    
    if (title != null) {
        NotificationCompat.Builder notify = ...
        ...
    }
    

    You might also want to change the contactExists() method name, since it's now returning the display name.