获取Google Drive API Android的资源ID

3
我正在使用Drive API在Google Drive的隐藏应用程序文件夹中创建文件。我想获取该文件的资源ID,但它一直返回null。以下是代码。一旦创建文件,它应该在回调中获取文件资源ID,但它返回null。它可以获取正常的Drive,但这完全没有帮助,因为获取Drive 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个回答

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>

如何将此内容整合到我的上述代码中?谢谢您的回复 :) - Jordan
1
只需创建新类即可。它将像广播接收器一样为您工作。在将文件上传到驱动器后,始终运行该方法。不要忘记在清单文件中定义它。我现在不在线,无法为您发布它。稍后我会发布它。 - Bui Quang Huy
我正在运行哪个方法,或者在上传文件后如何将GoogleDriveEventService类用作方法。 - Jordan
我将该类添加到我的应用程序中,并更新了清单文件,但在调试应用程序时,该类在文件创建后不会运行。我该如何使应用程序运行代码? - Jordan
你好,这个有帮到你吗?如果是的话,请考虑接受我的答案,这样其他人也可以使用这个解决方案。 - Bui Quang Huy
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接