如何从Android中的特定联系人读取收件箱短信?

时间:2018-04-14 20:14:23

标签: java android sqlite

我正在尝试从内容提供商处读取短信。我有以下代码

Uri uri = Uri.parse(SMS_URI_INBOX);
String whereClause = "address=?";
String[] whereArgs = {address};
String[] projection = new String[] { "*" };  
Cursor cur = getContentResolver().query(uri, projection, whereClause,whereArgs, "date desc");

除非各种格式的地址出现,否则一切正常。一种类型的地址可以用各种方式表示,例如" + 9198765443210"," +91 987 65443210" ," +91(987)65443210"," 098765443210"等等......这些类型的各种地址格式也存在于SMS内容提供商中。

方法1
最初我将所有地址转换为格式,其中特殊字符被%替换为 +9198765443210 - > %98765443210%
+91 987 65443210 - > %987%65443210%
然后使用 String whereClause = "address LIKE ?";
但失败,因为我们可能会发出查询address LIKE %98765443210%,但短信内容提供商的地址为+91 987 65443210.

android中是否存在类似normalized_address的东西,我们可以用来从SMS内容提供商那里获取数据?

1 个答案:

答案 0 :(得分:1)

追加@MikeM。评论,下面的代码帮助我获得了使用我在SMS内容提供商中进行查询的threadId

//Getting thread Id
ContentResolver mContentResolver = context.getContentResolver();
Uri uriSmsURI1 = Uri.withAppendedPath(Telephony.MmsSms.CONTENT_FILTER_BYPHONE_URI, address);
String[] projection1 = {this.threadId};
Cursor c1 = dbService.query(mContentResolver, uriSmsURI1, projection1, null, null, null);
if(c1.getCount()==0) {
    log.error(methodName, "Got count: "+c1.getCount()+" While looking for ThreadID");
        return null;
}
String threadId = null;
while(c1.moveToNext()){
    threadId = c1.getString(c1.getColumnIndexOrThrow(this.threadId));
}
c1.close();