Question

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();
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top