How to get contact name when receiving SMS

丶灬走出姿态 提交于 2019-12-04 13:40:12
Geethu

Try this code

In Broadcast Receiver

 public class SMSReceiver  extends BroadcastReceiver{

 String str = "";    
 String no = "";
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

     Bundle bundle = intent.getExtras();  
        SmsMessage[] msgs = null;
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            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]);                

                str += msgs[i].getMessageBody().toString();
                str += "\n";    
                no = msgs[i].getOriginatingAddress();

                //Resolving the contact name from the contacts.
                Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(no));
                Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
                try {
                    c.moveToFirst();
                 String  displayName = c.getString(0);
                String ContactName = displayName;   
                Toast.makeText(context, ContactName, Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    // TODO: handle exception
                }finally{
                    c.close();
                }

            }
        }
    }
}

You have to register this broadcast receiver in the manifest with intentfilter

    <receiver android:name="SMSReceiver">

         <intent-filter> 
             <action android:name= "android.provider.Telephony.SMS_RECEIVED" />
         </intent-filter> 

    </receiver>

ALso you have to add user permission like

<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!