Android - Querying the SMS ContentProvider?

喜夏-厌秋 提交于 2019-11-27 17:28:23
Macarse

This was already discussed.

To read SMS from the Content provider check: - android-1-5-reading-sms-messages

Check this threads:

About your comment saying that you are deleting a whole thread instead of a single sms: Have you tried out this code?

The address column contains the telephone number of the sms sender.

Use cursor.getString(cursor.getColumnIndex("address")) to pull the telephone number as a String. Pop a cursor on content://sms and sort it in date descending order to get the most recent message. You will have to wait for the new message to enter the table otherwise you will pull information from the wrong message. In an incomingSMS broadcastReceiver use a while loop, in a thread, polling for the cursor.getCount() to change. Then after the while loop cursor.moveToFirst will be the new message.

For example:

Cursor cur = getContentResolver().query(Uri.parseUri(content://sms), null, null, null, null);
int count = cur.getCount();
while (cur.getCount() == count)
{
     Thread.sleep(1000);
     cur = getContentResolver().query(Uri.parseUri(content://sms), null, null, null, null);
}

Then get the address of the sms sender:

cur = getContentResolver().query(Uri.parseUri(content://sms), null, null, null, "date DESC");

cur.MoveToFirst();
String telephoneNumber = cur.getString(cur.getColumnIndex("address");

This while loop will pause the thread until the new message arrives. You can also use a contentObserver, but this while loop is simple and does not require registration, unregistration, and a separate class.

Frankly I think its faster to pull the address and the body of the message directly from the pdu of the incoming intent. This way you dont have to wait for the message to enter the table to get the address and the body. The Android class SmsMessage has a variety of useful methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!