简体   繁体   中英

Android: Get DriveId for restore

My app takes a cloud-based backup on Google Drive. The backup occurs smoothly.

I use the following code for backup:

void saveToDrive() {
    // Code to upload file
    DriveId mDriveId = metadataResult.getMetadata().getDriveId();
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), MODE_PRIVATE);
    sharedPreferences.edit().putString("DriveId", mDriveId.encodeToString()).apply();
    ....
}

As you can see, I save the DriveId to SharedPreferences when I backup. So using that DriveId , I can restore as:

void readFromDrive(DriveId mDriveId) { // DriveId is not available after app reinstall!!
    // Code to download file and restore
}

My restore operation requires a DriveId to download the backed-up file. I want to trigger a restore when the app is reinstalled . But, I am not able to get the DriveId so that I may download the required file.

How do I do that? Please, I am desperate for some help.

Thanks.

I solved it by first querying the contents of Google Drive using the code:

public class GDriveQuery extends BaseDemo {
    @Override
    public void onConnected(Bundle connectionHint) {
        super.onConnected(connectionHint);
        Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, "field"))
            .addFilter(Filters.not(Filters.eq(SearchableField.TRASHED, true)))
            .build();
        Drive.DriveApi.query(getGoogleApiClient(), query)
            .setResultCallback(metadataCallback);
    }

    final private ResultCallback<DriveApi.MetadataBufferResult> metadataCallback =
        new ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while retrieving results");
                    return;
                }
                System.out.println("SUCCESS!!");
                MetadataBuffer mdb;
                mdb = result.getMetadataBuffer();
                for (Metadata md : mdb) {
                    System.out.println(md.getDriveId().encodeToString());
                }
            }
        };
}

The above code returned me the DriveId . And then using that DriveId I used the function readFromDrive(driveId) as posted in the question above.

It works!!

Thanks guys for all your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM