I have an app that needs to implement a 'share' option to transfer data contained in the device's local database to another device, where that device can take this data and insert it into the appropriate tables in the device's database.
I have communication working over bluetooth, I'm just looking for a good way to transfer this data across. Is there an easy way to do an sqlite dump on device A, transfer this across to device B using bluetooth, and have device B reinsert this data?
解决方案
Implementing aContentProvider is how you leverage the Android framework to do CRUD operations on a database.
A good way could be to transform a row into Json and unpackage that string on the receiving side to insert it. This way is more testable, easier to recover from errors during send, but might be very slow depending on the size of your data. For speeding it up I would send multiple rows in batches and test to see what batch size would be best for speed and reliability.
A fast way might be to dump the data to flat file then use the FileProvider to provide access to that file as a URI and try something like the following from here
public void sendFile(Uri uri, BluetoothSocket bs) throws IOException {
BufferedInputStream bis = new BufferedInputStream(getContentResolver().openInputStream(uri));
OutputStream os = bs.getOutputStream();
try {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = bis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
bis.close();
os.flush();
os.close();
bs.close();
}
}