计算单个线程的已发送短信
Count sent sms messages for a single thread
我正在查找特定线程(例如,id 为 15)中已发送短信的计数。我发现了这个 How do I get the count of SMS messages per contact into a textview? <-- 但它并没有解决我的问题,因为它计算了发送和接收的短信。是否可以只计算已发送的消息?我想我可以查询 "content://sms/sent" 并遍历每条短信,但我想知道是否有更有效的方法。
谢谢
您可以使用线程 ID 查询 Sms.Conversations
,并选择将 TYPE
列限制为 MESSAGE_TYPE_SENT
。由于您只需要计数,我们可以执行 SELECT COUNT()
查询,因此不会浪费资源来构建具有未使用值的 Cursor
。例如:
private int getThreadSentCount(String threadId) {
final Uri uri = Sms.Conversations.CONTENT_URI
.buildUpon()
.appendEncodedPath(threadId)
.build();
final String[] projection = {"COUNT(1)"};
final String selection = Sms.TYPE + "=" + Sms.MESSAGE_TYPE_SENT;
int count = -1;
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri,
projection,
selection,
null,
null);
if (cursor != null && cursor.moveToFirst()) {
count = cursor.getInt(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return count;
}
上面使用的Sms
class在android.provider.Telephony
class.
import android.provider.Telephony.Sms;
供参考,Sms.Conversations.CONTENT_URI
相当于Uri.parse("content://sms/conversations")
,Sms.TYPE
相当于"type"
,Sms.MESSAGE_TYPE_SENT
相当于2
。
我正在查找特定线程(例如,id 为 15)中已发送短信的计数。我发现了这个 How do I get the count of SMS messages per contact into a textview? <-- 但它并没有解决我的问题,因为它计算了发送和接收的短信。是否可以只计算已发送的消息?我想我可以查询 "content://sms/sent" 并遍历每条短信,但我想知道是否有更有效的方法。
谢谢
您可以使用线程 ID 查询 Sms.Conversations
,并选择将 TYPE
列限制为 MESSAGE_TYPE_SENT
。由于您只需要计数,我们可以执行 SELECT COUNT()
查询,因此不会浪费资源来构建具有未使用值的 Cursor
。例如:
private int getThreadSentCount(String threadId) {
final Uri uri = Sms.Conversations.CONTENT_URI
.buildUpon()
.appendEncodedPath(threadId)
.build();
final String[] projection = {"COUNT(1)"};
final String selection = Sms.TYPE + "=" + Sms.MESSAGE_TYPE_SENT;
int count = -1;
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri,
projection,
selection,
null,
null);
if (cursor != null && cursor.moveToFirst()) {
count = cursor.getInt(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return count;
}
上面使用的Sms
class在android.provider.Telephony
class.
import android.provider.Telephony.Sms;
供参考,Sms.Conversations.CONTENT_URI
相当于Uri.parse("content://sms/conversations")
,Sms.TYPE
相当于"type"
,Sms.MESSAGE_TYPE_SENT
相当于2
。