Skip to content

Instantly share code, notes, and snippets.

@frontrangerider2004
Created July 31, 2016 19:45
Show Gist options
  • Save frontrangerider2004/91fee3083bfd4920a5b2a6318c4d7174 to your computer and use it in GitHub Desktop.
Save frontrangerider2004/91fee3083bfd4920a5b2a6318c4d7174 to your computer and use it in GitHub Desktop.
Threaded and Queued Heavy R/W For Android Databases
/**
Android service skeleton that performs intensive off main thread database operations.
This example uses a HandlerThread which will queue up requests rather than parallelize
them, which is good for database operations.
*/
public class MyDatabaseService extends Service {
private HandlerThread databaseThread;
private Handler databaseHandler;
private MyDatabaseHelper dbHelper;
public void onCreate(){
databaseThread = new HandlerThread("Database");
databaseThread.start();
databaseHandler = new Handler(databaseThread.getLooper());
dbHelper = new MyDataBaseHelper(geApplicationContext);
}
/*
Great pattern for heavy r/w operations that might require some post processing.
This allows us to synchronize on the Service Class that maintains the SQLite DB
so we block here until the r/w portion is done, then we unblock and allow for
post processing while another thread can perform r/w again.
*/
public void someQueuedOffThreadDatabaseOperation(){
databaseHandler.post(new Runnable() {
@Override
public void run() {
synchronized (MyDatabaseService.this){
try{
dbHelper.doMyBidding(<my-params>);
}
catch (Exception e){
Log.e(TAG, e.getMessage());
}
finally{
dbHelper.close();
}
}//End synchronized
}//End run
});//End Runnable
}//End Method
}//End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment