Android - Querying the SMS ContentProvider?

前端 未结 2 1183
名媛妹妹
名媛妹妹 2020-12-04 11:58

I currently register a content observer on the following URI \"content://sms/\" to listen out for incoming and outgoing messages being sent.

This seems to work ok an

相关标签:
2条回答
  • 2020-12-04 12:09

    This was already discussed.

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

    Check this threads:

    • delete-sms-in-android-1-5
    • how-to-delete-sms-from-inbox-in-android-programmatically
    • can-we-delete-an-sms-in-android-before-it-reaches-the-inbox

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

    0 讨论(0)
  • 2020-12-04 12:19

    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.

    0 讨论(0)
提交回复
热议问题