gpt4 book ai didi

Android - contentResolver.notifyChange() 降低性能

转载 作者:行者123 更新时间:2023-11-29 15:13:49 27 4
gpt4 key购买 nike

我有一个覆盖 bulkInsert() 的 MyContentProvider 类。在此方法中,我使用 SQLite 事务将大约 4,000 行插入数据库,这在三星 Galaxy S4 设备上大约需要 25 秒。

但是,当我从我的 bulkInsert() 方法中删除这一行时...

getContext().getContentResolver().notifyChange(insertedId, null);

...总插入时间下降到大约 1 或 2 秒。

那么,有没有更好的方法来调用notifyChange()

我试过在另一个线程中调用它,就像这样......

                    new Thread(new Runnable() {
public void run() {
getContext().getContentResolver().notifyChange(insertedId, null);
}
}).start();

...但它仍然很慢,并且由于某种原因导致 OutOfMemoryError

为了完整起见,这是我的 bulkInsert() 方法...

    @Override
public int bulkInsert(Uri uri, ContentValues[] valuesArray) {

/*
* Open a read / write database to support the transaction.
*/
SQLiteDatabase db = dbHelper.getWritableDatabase();

String tableName;

switch (uriMatcher.match(uri)) {
case BRANDS_SEARCH:
tableName = BRAND_NAMES_TABLE;
break;
case PRODUCTS_SEARCH:
tableName = PRODUCTS_TABLE;
break;
case PARENT_COMPANIES_SEARCH:
tableName = PARENT_COMPANIES_TABLE;
break;
case PRODUCTS_DATA_SEARCH:
tableName = PRODUCTS_DATA_TABLE;
break;
default:
//break;
throw new IllegalArgumentException("Unsupported URI: " + uri);
}

/*
* Begin the transaction
*/
db.beginTransaction();

int numSuccessfulInsertions = 0;

try {

for (int i = 0; i < valuesArray.length; i++) {

/*
* Insert the values into the table
*/
long rowId = db.insert(tableName, null, valuesArray[i]);

if (rowId > -1) {

/*
* Increment numSuccessfulInsertions
*/
numSuccessfulInsertions++;

/*
* Construct the URI of the newly inserted row.
*/
Uri insertedId = ContentUris.withAppendedId(uri, rowId);

/*
* Notify any observers of the change in the data set.
*/
getContext().getContentResolver().notifyChange(insertedId, null);



}
else {

/*
* Don't give up (as not all insert attempts need to succeed)
*/
//throw new Exception("Could not insert row");
}

}

/*
* Return number of successful insertions
*/
return numSuccessfulInsertions;
}
catch(Exception e) {

Log.e(LOG_TAG, "bulkInsert exception", e);

/*
* Return number of successful insertions
*/
return numSuccessfulInsertions;

}
finally {

/*
* Some (or all) insertion attempts succeeded
*/
db.setTransactionSuccessful();

/*
* Always end the transaction
*/
db.endTransaction();
}
}

最佳答案

为批量操作通知一次,而不是为每条插入的记录通知一次。将您的调用移至 notifyChange,使其遵循 for 循环。

关于Android - contentResolver.notifyChange() 降低性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com