我想删除手机上的所有短信,除了每次会话的最后500条短信。 这是我的代码,但速度非常慢(删除一条短信大约需要10秒钟)。 我如何加快这段代码:
ContentResolver cr = getContentResolver();
Uri uriConv = Uri.parse("content://sms/conversations");
Uri uriSms = Uri.parse("content://sms/");
Cursor cConv = cr.query(uriConv,
new String[]{"thread_id"}, null, null, null);
while(cConv.moveToNext()) {
Cursor cSms = cr.query(uriSms,
null,
"thread_id = " + cConv.getInt(cConv.getColumnIndex("thread_id")),
null, "date ASC");
int count = cSms.getCount();
for(int i = 0; i < count - 500; ++i) {
if (cSms.moveToNext()) {
cr.delete(
Uri.parse("content://sms/" + cSms.getInt(0)),
null, null);
}
}
cSms.close();
}
cConv.close();
答案 0 :(得分:4)
您可以做的主要事情之一是batch ContentProvider operations,而不是进行33,900次单独删除:
// Before your loop
ArrayList<ContentProviderOperation> operations =
new ArrayList<ContentProviderOperation>();
// Instead of cr.delete use
operations.add(new ContentProviderOperation.newDelete(
Uri.parse("content://sms/" + cSms.getInt(0))));
// After your loop
try {
cr.applyBatch("sms", operations); // May also try "mms-sms" in place of "sms"
} catch(OperationApplicationException e) {
// Handle the error
} catch(RemoteException e) {
// Handle the error
}
向上指示您是要为每个对话执行一次批处理操作还是对整个SMS历史记录执行一次批处理操作。