获取Google Drive API Android

时间:2016-04-14 01:13:04

标签: android google-drive-android-api

我正在使用驱动器API在google驱动器上的隐藏应用文件夹中创建一个文件。我想获取该文件的资源ID,但它一直返回null。这是代码。创建文件后,它应该在回调中获取文件资源ID,但它返回null。它获得了正常的驱动器,但它完全没有帮助,因为获取驱动器ID需要资源ID。关于如何获取资源ID的任何想法。我已经检查了多个关于此的不同链接,所有这些都没有帮助。

//<editor-fold desc="Variables">

// Define Variable Int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE//
public static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 0;

// Define Variable int RESOLVE_CONNECTION_REQUEST_CODE//
public static final int RESOLVE_CONNECTION_REQUEST_CODE = 3;

// Define Variable GoogleApiClient googleApiClient//
public GoogleApiClient googleApiClient;

// Define Variable String title//
String title = "Notes.db";

// Define Variable String mime//
String mime = "application/x-sqlite3";

// Define Variable String currentDBPath//
String dBPath = "/School Binder/Note Backups/Notes.db";

// Define Variable File data//
File data = Environment.getExternalStorageDirectory();

// Define Variable File dbFile//
File dbFile = new File(data, dBPath);

// Create Metadata For Database Files//
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(title).setMimeType(mime).build();

String EXISTING_FILE_ID = "CAESABjaBSCMicnCsFQoAA";

//</editor-fold>

// Method That Runs When Activity Starts//
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initiate allowWriteExternalStorage Method//
    allowWriteExternalStorage();

    // Initiate connectToGoogleDrive Method//
    connectToGoogleDrive();
}

// Method That Runs When App Is Resumed//
protected void onResume() {
    super.onResume();

    // Checks If Api Client Is Null//
    if (googleApiClient == null) {

        // Create Api Client//
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    // Attempt To Connect To Google drive//
    googleApiClient.connect();
}

// Method That Runs When App is paused//
@Override
protected void onPause() {

    // Checks If Api Was Used//
    if (googleApiClient != null) {

        // Disconnect From Google Drive//
        googleApiClient.disconnect();
    }
    super.onPause();
}

// Method That Runs When App Is Successfully Connected To Users Google Drive//
@Override
public void onConnected(@Nullable Bundle bundle) {

    // Add New File To Drive//
    Drive.DriveApi.newDriveContents(googleApiClient).setResultCallback(contentsCallback);

}

// Method That Runs When Connection Is Suspended//
@Override
public void onConnectionSuspended(int i) {

}

// Method That Runs When App Failed To Connect To Google Drive//
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    // Checks If Connection Failure Can Be Resolved//
    if (connectionResult.hasResolution()) {

        // If Above Statement Is True, Try To Fix Connection//
        try {

            // Resolve The Connection//
            connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE);

        } catch (IntentSender.SendIntentException ignored) {
        }

    } else {

        // Show Connection Error//
        GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show();
    }
}

// Method That Gives App Permission To Access System Storage//
public void allowWriteExternalStorage() {

    // Allow Or Un - Allow Write To Storage//
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Request To Write To External Storage//
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);

    }
}

// Method That Connects To Google Drive//
public void connectToGoogleDrive() {

    // Create Api Client//
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addScope(Drive.SCOPE_APPFOLDER)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    // Attempt To Connect To Google drive//
    googleApiClient.connect();
}

//<editor-fold desc="Contents Callback">

// What Happens When App Is Trying To Make A New File Or Folder//
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {

    @Override
    public void onResult(@NonNull DriveApi.DriveContentsResult result) {

        // Runs When File Failed To Create//
        if (!result.getStatus().isSuccess()) {

            // Log That File Failed To Create//
            Log.d("log", "Error while trying to create new file contents");

            return;
        }

        // Checks If Creating File Was Successful//
        DriveContents cont = result.getStatus().isSuccess() ? result.getDriveContents() : null;

        // Write File//
        if (cont != null) try {
            OutputStream oos = cont.getOutputStream();
            if (oos != null) try {
                InputStream is = new FileInputStream(dbFile);
                byte[] buf = new byte[5000];
                int c;
                while ((c = is.read(buf, 0, buf.length)) > 0) {
                    oos.write(buf, 0, c);
                    oos.flush();
                }
            } finally {

                oos.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // Put File In User Hidden App Folder//
        Drive.DriveApi.getAppFolder(googleApiClient).createFile(googleApiClient, meta, cont).setResultCallback(fileCallback);
    }
};

//</editor-fold>

//<editor-fold desc="File Callback">

// What Happens If File IS mAde Correctly Or In-Correctly//
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {

    @Override
    public void onResult(@NonNull DriveFolder.DriveFileResult result) {

        // Checks If It Failed//
        if (!result.getStatus().isSuccess()) {

            Log.d("log", "Error while trying to create the file");
            return;
        }

        Drive.DriveApi.requestSync(googleApiClient);

        Log.d("log", "Created a file in App Folder: " + result.getDriveFile().getDriveId());

        String File_ID = String.valueOf(result.getDriveFile().getDriveId().getResourceId());

        Drive.DriveApi.fetchDriveId(googleApiClient, File_ID).setResultCallback(idCallback);
    }
};

//</editor-fold>

//<editor-fold desc="Id Callback">

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {

            Log.d("Message", "Cannot find DriveId. Are you authorized to view this file?");

            return;
        }
        DriveId driveId = result.getDriveId();
        DriveFile file = driveId.asDriveFile();
        file.getMetadata(googleApiClient)
                .setResultCallback(metadataCallback);
    }
};

//</editor-fold>

//<editor-fold desc="metadata Callback">

final private ResultCallback<DriveResource.MetadataResult> metadataCallback = new
        ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {

                    Log.d("Message", "Problem while trying to fetch metadata");
                    return;
                }
                Metadata metadata = result.getMetadata();

                Log.d("Message", "Metadata successfully fetched. Title: " + metadata.getTitle());
            }
        };

//</editor-fold>
}

1 个答案:

答案 0 :(得分:4)

不要这样做,让我们扩展DriveEventService来处理这项任务:

public class GoogleDriveEventService extends DriveEventService {
    private static final String TAG = "GoogleDriveEventService";

    @Override
    public void onCompletion(CompletionEvent event) {
        super.onCompletion(event);
        DriveId driveId = event.getDriveId();
        String resourceId = driveId.getResourceId();

    }    
}

更新 AndroidManifest.xml

<service
    android:name="training.com.services.GoogleDriveEventService" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/>
    </intent-filter>
</service>