Cyt*_*tus 14 android google-drive-api google-drive-android-api
我已经设法在SD卡上创建我的数据库备份并从那里恢复,但意识到我的备份的目的是确保数据的安全性,在这种情况下,如果物理设备本身损坏,丢失或自发地燃烧SD卡上的备份.因此,在这种情况下将备份放在与原始备份相同的位置,坦率地说,无法实现备份的目的.
因此,我想使用Google Drive作为保存db文件更安全的地方,而且它是免费的.我已经看了谷歌的快速启动演示,我工作得很好.但我仍然不知道如何为我的案子做到这一点.
我发现了一些代码,但仍然使用了一些弃用的方法,到目前为止,我只是在省略不推荐使用的区域时设法运行它,但它只在我的Google云端硬盘中创建了一个空白的二进制文件,所以我认为不推荐使用的区域是实际上传数据库备份内容的地方.如果有人可以提供帮助,那将非常感激.
我会把它留在下面,万一有人可以用它来更好地向我解释.我还在下面标记了已弃用的方法,它已接近尾声.
public class ExpectoPatronum extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "demodb";
private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_backup";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
@Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
@Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt("error", result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), "errordialog");
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
DriveContents content = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
in.close();
commitAndCloseContents is DEPRECATED -->/**mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status result) {
// Handle the response status
}
});**/
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
@Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt("error");
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
((ExpectoPatronum) getActivity()).onDialogDismissed();
}
}
}
Run Code Online (Sandbox Code Playgroud)
用于访问Google云端硬盘的两个API都处理二进制内容.因此,您唯一需要做的就是上传二进制数据库文件,为其提供正确的MIME类型和NAME(标题).
API的选择取决于您,GDAA的行为类似于"本地"实体,上传/下载由Google Play服务处理,REST Api更低级别,为您提供更多控制,但您必须处理网络问题(wifi开/关等),即你通常必须建立一个同步服务来这样做.使用GDAA,GooPlaySvcs为您完成.但我离题了.
我可以指出你最近的这个GitHub演示(GooPlaySvcs 7.00.+),我用来测试不同的REST/GDAA问题.MainActivity有点复杂,因为它允许在不同的Google帐户之间切换,但如果您遇到这些障碍,则可以使用REST或GDAA CRUD包装.
看看这一行.byte []缓冲区包含二进制JPEG数据,它带有"image/jpeg"mime类型(和基于时间的名称).如果使用如下结构将DB文件加载到byte []缓冲区中,则唯一需要做的事情是:
private static final int BUF_SZ = 4096;
static byte[] file2Bytes(File file) {
if (file != null) try {
return is2Bytes(new FileInputStream(file));
} catch (Exception ignore) {}
return null;
}
static byte[] is2Bytes(InputStream is) {
byte[] buf = null;
BufferedInputStream bufIS = null;
if (is != null) try {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
bufIS = new BufferedInputStream(is);
buf = new byte[BUF_SZ];
int cnt;
while ((cnt = bufIS.read(buf)) >= 0) {
byteBuffer.write(buf, 0, cnt);
}
buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
} catch (Exception e) {le(e);}
finally {
try {
if (bufIS != null) bufIS.close();
} catch (Exception e) {le(e);}
}
return buf;
}
Run Code Online (Sandbox Code Playgroud)
我现在不记得SQLite DB的MIME类型了,但是我确信它可以完成,因为我只做了一次(不幸的是代码现在已经消失).我记得我实际上可以使用一些网络应用程序访问和修改SQL中的SQLite数据库.
祝好运
更新:
在我写完上面的咆哮后,我看了你正在谈论的演示.如果你有它工作,最简单的方法是在这里插入你的数据库文件,设置正确的MIME,你很高兴.带你去挑选.
并解决您的"已弃用"问题.GDAA仍在开发中,快速启动已有一年多了.这就是我们生活的世界:-)
| 归档时间: |
|
| 查看次数: |
15328 次 |
| 最近记录: |