我在 Android 中创建了 SQLite 数据库的备份,并希望将其同步到 Google Drive。备份未同步,以下代码没有错误:
public class Synchorize extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
private static Drive service;
private static Uri fileUri;
private GoogleAccountCredential credential;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.synchronize);
credential = GoogleAccountCredential.usingOAuth2(this,
Arrays.asList(DriveScopes.DRIVE));
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null
&& data.getExtras() != null) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
saveFileToDrive();
}
}
break;
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// File's binary content
fileUri = Uri
.fromFile(new java.io.File(
Environment.getDataDirectory().getPath()
+ "/data/com.example.note_taking/databases/notes.db"));
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent(getMimeType("db"), fileContent);
// File's metadata.
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType(getMimeType("db"));
com.google.api.services.drive.model.File file = service
.files().insert(body, mediaContent).execute();
if (file != null) {
Toast.makeText(getApplicationContext(),
"Backup Uploaded Successfully",
Toast.LENGTH_LONG).show();
finish();
}
} catch (UserRecoverableAuthIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
public String getMimeType(String url) {
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
url);
return mimeType;
}
}