【问题标题】:Delete SMS with contentResolver is too slow用 contentResolver 删除短信太慢了
【发布时间】:2014-01-14 19:06:23
【问题描述】:

我想删除我手机上的所有短信,每次对话的最后 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();

【问题讨论】:

  • 你有多少对话?当您删除时,您每次对话总共有多少条短信?
  • 我有大约 34000 条短信和大约 100 个对话。但一次对话有 26000 条短信
  • 考虑到您在数据库上执行条件双光标操作,我想这是一个相当不错的时间。这还取决于您使用的手机。
  • 我有一个 Xperia S,我尝试在另一个版本中在删除之前关闭两个光标,但它仍然很慢

标签: android sms android-contentresolver


【解决方案1】:

您可以做的主要事情之一是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 历史记录执行一个批处理操作。

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2014-06-07
    相关资源
    最近更新 更多