0

我使用的是 2.1 平台,我可以使用下面的代码检索短信详细信息。但是只显示号码和短信正文,名称还没有出现,我该怎么做才能检索名称呢?

代码

public class SMSActivity extends Activity {

    ListView lview;
    String Body  = "" ; 
    ArrayList<String> smslist=new ArrayList<String>();
    ArrayAdapter<String> itemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);
    lview =(ListView)findViewById(R.id.lv);
    itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smslist);
    lview.setAdapter(itemAdapter);

    ContentResolver cr = getContentResolver();
    Cursor c = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
    while(c.moveToNext()){

    Number = c.getString(c.getColumnIndexOrThrow("address"));

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();

   smslist.add( Number + ":" +"\n"+ Body);
    }
    itemAdapter.notifyDataSetChanged();

    c.close();
}
} 

如何解决这个问题呢 ?

4

1 回答 1

0

你的号码是对的!!现在将此号码传递给此方法,它将返回您相应号码的联系人姓名。

   public String getContactName(String number) {
        String cName = null;
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
        String nameColumn[] = new String[]{PhoneLookup.DISPLAY_NAME};
        Cursor c =  getContentResolver().query(uri, nameColumn, null, null, null);
        if(c == null || c.getCount() == 0)
            return cName;
        c.moveToFirst();
        cName = c.getString(0);
        return cName;

    }

添加以下权限

<uses-permission android:name="android.permission.READ_CONTACTS" />

在您的清单文件中到 Read_contact 数据。

为您的代码替换此代码

Number = c.getString(c.getColumnIndexOrThrow("address"));

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();

   smslist.add( Number + ":" +"\n"+ Body);

与下面

   Number = c.getString(c.getColumnIndexOrThrow("address"));
   String name = getContactName(Number); // declare name outside

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();
  if( name == null )
     smslist.add( Number + ":" +"\n"+ Body);
  else
        smslist.add( name + ":" +"\n"+ Body);
于 2012-07-12T12:16:22.510 回答