Android : Catching Outgoing SMS using ContentObserver or receiver not working

时光怂恿深爱的人放手 提交于 2019-12-01 09:18:53

There is no "android.provider.Telephony.SMS_SENT" action in the SDK, nor is there any system-wide broadcast upon an SMS send, so your second method isn't going to work.

As for the ContentObserver, the Uri you register for must be the base Uri for the SMS Provider. That is, change Uri.parse("content://sms/out") to Uri.parse("content://sms"). If you want to handle only outgoing messages, you will have to query the Provider in the onChange() method, and retrieve the type column value for the message, checking for a value of 2, which indicates a sent message.

If you're supporting an API level lower than 16, then it would be something like this:

private static final Uri uri = Uri.parse("content://sms");  
private static final String COLUMN_TYPE = "type";
private static final int MESSAGE_TYPE_SENT = 2;
...

@Override
public void onChange(boolean selfChange) {
    Cursor cursor = null;

    try {
        cursor = resolver.query(uri, null, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            int type = cursor.getInt(cursor.getColumnIndex(COLUMN_TYPE));

            if (type == MESSAGE_TYPE_SENT) {
                // Sent message
            }
        }
    }
    finally {
        if (cursor != null)
            cursor.close();
    }
}

Starting with API 16, the ContentObserver class offers an onChange() overload that will provide the specific Uri for the message as the second parameter, which you can query and inspect more efficiently than the base Uri. Also, if your minimum API level is 19, there are several classes with constants that you can substitute for those defined in the example code above.

As a side note, the Uri for the outbox is "content://sms/outbox", not "content://sms/out".

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