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

前端 未结 2 1478
离开以前
离开以前 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:28

    Uri uriInbox = Uri.parse("content://sms/inbox");
    
                Cursor c = getContentResolver().query(uriInbox, null, null, null, null); 
    
    
                if (c.moveToFirst()) {
                    for (int i = 0; i < c.getCount(); i++) {
                        String name = null;
                        String phone = "";
                        String _id = c.getString(c.getColumnIndexOrThrow("_id"));
                        String thread_id = c.getString(c.getColumnIndexOrThrow("thread_id"));
                        String msg = c.getString(c.getColumnIndexOrThrow("body"));
                        String type = c.getString(c.getColumnIndexOrThrow("type"));
                        String timestamp = c.getString(c.getColumnIndexOrThrow("date"));
                        phone = c.getString(c.getColumnIndexOrThrow("address"));
                        name = Function.getContactbyPhoneNumber(getApplicationContext(), c.getString(c.getColumnIndexOrThrow("address")));
    
    
                        c.moveToNext();
                    }
                }
                c.close();
    

    Finally your getContactbyPhoneNumber method:

    public String getContactbyPhoneNumber(Context c, String phoneNumber) {
    
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME};
        Cursor cursor = c.getContentResolver().query(uri, projection, null, null, null);
    
        if (cursor == null) {
            return phoneNumber;
        }else {
            String name = phoneNumber;
            try {
    
                if (cursor.moveToFirst()) {
                    name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
                }
    
            } finally {
                cursor.close();
            }
    
            return name;
        }
    }
    

    Courtesy: http://www.androstock.com/tutorials/create-sms-app-android-android-studio-part-2.html

提交回复
热议问题