How do i get the SMS Sender Contact (Person) saved name using “content://sms/inbox”

前端 未结 2 1497
离开以前
离开以前 2020-12-17 19:58

In my App i want to retrieve the SMS sender saved Name using below code but it always return null. Please suggest me whats the convenient way to get the sender name.

2条回答
  •  被撕碎了的回忆
    2020-12-17 20:16

    By this way you can get the saved contact name from inbox.. call the method getAllSms() to get the details..

     public void getAllSms() {
        Uri message = Uri.parse("content://sms/");
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(message, null, null, null, null);
        startManagingCursor(c);
        int totalSMS = c.getCount();
        if (c.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
    
                Log.d("SMSss",
                        "Contact number : "
                                + c.getString(c
                                        .getColumnIndexOrThrow("address"))
                                + "\n"
                                + "msg : "
                                + c.getColumnIndexOrThrow("body")
                                + "\n"
                                + "ID : "
                                + c.getString(c.getColumnIndexOrThrow("_id"))
                                + "\n"
                                + "Person : "
                                + getContactName(
                                    getApplicationContext(),
                                        c.getString(c
                                                .getColumnIndexOrThrow("address"))));
    
                c.moveToNext();
            }
        }
        c.close();
    
    }
    
    public String getContactName(Context context, String phoneNumber) {
        ContentResolver cr = context.getContentResolver();
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNumber));
        Cursor cursor = cr.query(uri,
                new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
        if (cursor == null) {
            return null;
        }
        String contactName = null;
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor
                    .getColumnIndex(PhoneLookup.DISPLAY_NAME));
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        return contactName;
    }
    

提交回复
热议问题