问题
I'm learning more about content providers in Android and they're performance. For example, if I write my own content provider (subclass ContentProvider) for SQLite operations and then I want to do an operation in an Activity's onPause() method, then in my Activity I would do:
@Override
protected void onPause (){
super.onPause();
// ...prepare myTransactionValues
// This could be anything like insert, bulkInsert, query, delete, etc.
getContentResolver().insert(CONTENT_URI, myTransactionValues)
}
However, it looks likes this database operation is being done on the main thread. Is the work being done in a separate thread behind the scenes? Should it be in it's own thread? If it should, is there a recommended way (perhaps a Service)?
回答1:
If you want to do something in a Non-UI thread, you should usually use an AsyncTask. A service, on the other hand, is best kept for long tasks.
回答2:
The best way to use Content Providers is in AsyncTask because they are expensive operations that can't run in the main thread.
Android have encapsulated this pattern in what they call loaders they extend AsyncTaskLoader for do the job in a non UI thread use loaders callbacks and Cursors for retrieve data from the content provider.
来源:https://stackoverflow.com/questions/8392012/should-calls-to-a-content-resolver-be-done-in-a-service-i-e-separate-thread