如何接收短信时,你得到的联系人姓名 [英] How to get contact name when receiving SMS

查看:333
本文介绍了如何接收短信时,你得到的联系人姓名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code接收短信,我试图让联系人姓名。

I have the following code to receive an SMS and I am trying to get the contact name.

package com.example.smsTest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {
    private SQLiteAdapter mySQLiteAdapter;

    @Override
    public void onReceive(Context context, Intent intent) {
        mySQLiteAdapter = new SQLiteAdapter(context);
        mySQLiteAdapter.openToRead();

        Message message = null;

        Bundle extras = intent.getExtras();
        if (extras == null)
            return;

        Object[] pdus = (Object[]) extras.get("pdus");
        for (int i = 0; i < pdus.length; i++) {
            SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String sender = SMessage.getOriginatingAddress();
            String body = SMessage.getMessageBody().toString();

            message = mySQLiteAdapter.createMessage(sender, body);

            // A custom Intent that will used as another Broadcast
            Intent in = new Intent("SmsMessage.intent.MAIN").putExtra(
                    "get_msg", sender + ":" + body);

            // To display a Toast whenever there is an SMS.
            Toast.makeText(context, body, Toast.LENGTH_LONG).show();

            Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, SMessage.getOriginatingAddress());  

            Cursor cur = context.getContentResolver().query(personUri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null );  

            if( cur.moveToFirst() ) {  
                         int nameIndex = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);  

                         String PersonName = cur.getString(nameIndex); 

                         Toast.makeText(context, PersonName, Toast.LENGTH_LONG).show();
            }
            cur.close();

            // You can place your check conditions here(on the SMS or the
            // sender)
            // and then send another broadcast
            context.sendBroadcast(in);

            // This is used to abort the broadcast and can be used to silently
            // process incoming message and prevent it from further being
            // broadcasted. Avoid this, as this is not the way to program an
            // app.
            this.abortBroadcast();
        }
    }
}

这是我补充说,导致我的应用程序崩溃code:

This is the code that I have added that cause my app to crash:

Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, SMessage.getOriginatingAddress());  

Cursor cur = context.getContentResolver().query(personUri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null );  

if( cur.moveToFirst() ) {  
             int nameIndex = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);  

             String PersonName = cur.getString(nameIndex); 

             Toast.makeText(context, PersonName, Toast.LENGTH_LONG).show();
}
cur.close();

我只是修改了code从这个<一个答案href=\"http://stackoverflow.com/questions/4359564/how-to-get-the-contacts-display-name-in-sms-uri\">link.

现在应用程序崩溃接收短信时。

Now the app crashes when receiving an SMS.

推荐答案

试试这个code

在广播接收器

 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();
                }

            }
        }
    }
}

您在清单中注册该广播接收机的IntentFilter

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"/>

这篇关于如何接收短信时,你得到的联系人姓名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆