Delete SMS with contentResolver is too slow

こ雲淡風輕ζ 提交于 2019-12-20 03:53:24

问题


I would like to delete all SMS on my phone except the 500 last SMS for each conversation. This is my code but it's very slow (take about 10 seconds to delete one SMS). How I can speed up this code :

    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();

回答1:


One of the main things you can do is batch ContentProvider operations instead of doing 33,900 separate deletes:

// 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
}

Up you whether you want to do one batch operation per conversation or one batch operation for the entire SMS history.



来源:https://stackoverflow.com/questions/21121848/delete-sms-with-contentresolver-is-too-slow

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