通过内容获取每个短信的电话号码:// sms /

时间:2012-08-05 23:23:39

标签: android sms

我写了以下代码,以获得用户和数字之间的整个对话:

Uri SMS_INBOX = Uri.parse("content://sms/");
        String selection = "thread_id = " + thread_id;
        final String[] projection = new String[] { "*" };
        Cursor c = getContentResolver().query(SMS_INBOX, projection, selection,null, "date");

        startManagingCursor(c);

        String[] body = new String[c.getCount()];
        String[] address = new String[c.getCount()];
        if (c.moveToFirst()) {
            for (int j = 0; j < c.getColumnCount(); j++)
                Log.w("ColumnName", c.getColumnName(j));
            for (int i = 0; i < c.getCount(); i++) {
                body[i] = c.getString(c.getColumnIndexOrThrow("body")).toString();
                address[i] = c.getString(c.getColumnIndexOrThrow("address")).toString();
                Log.d("address-" + i, address[i]);
                Log.d("body-" + i, body[i]);
                String subject =  c.getString(c.getColumnIndexOrThrow("_id")).toString();
                Log.d("_id-" + i, subject);
                String thread =  c.getString(c.getColumnIndexOrThrow("thread_id")).toString();
                Log.d("thread_id-" + i, subject);
                Log.d("----", "----");

                c.moveToNext();
            }

        }

通过此代码,我可以获得对话中的所有消息。问题是,我无法弄清楚哪个号码正在发送哪个消息。如果我得到列“地址”它会一直返回相同的数字(实际上它只返回另一个人的号码),所以我无法记录我刚刚通过此代码获得的消息是由用户发送还是另一个号码。

1 个答案:

答案 0 :(得分:1)

该列将始终仅为第二个人提供数字。如果要区分已发送的消息和已接收的消息,则必须使用“类型”列。

body[i] = c.getString(c.getColumnIndexOrThrow("body")).toString();

if(c.getString(c.getColumnIndex("type")).equalsIgnoreCase("1")){

                // sms received

                msg_state[i]=1;

             }

              else {
                //sms sent
                msg_state[i]=0;

             }

否您可以轻松识别发送的短信并收到短信。