在主活动中使用谷歌云端硬盘 api 类助手



我有一个登录以驱动API的SplashActivity类:

private void handleSignInIntent(Intent data) {
GoogleSignIn.getSignedInAccountFromIntent(data).addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
@Override
public void onSuccess(GoogleSignInAccount googleSignInAccount) {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(SplashActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleSignInAccount.getAccount());
Drive googleDriveService = new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential)
.setApplicationName("MyApp")
.build();
DriveServiceHelper driveServiceHelper = new DriveServiceHelper(googleDriveService); //Need the driveServiceHelper
startApp(); //Goes to Main Activity
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}

这将创建 DriveServiceHelper 实例。我需要在主活动中使用此实例,如下所示:

private void uploadFile()
{
String filePath = "path";
driveServiceHelper.createFile(filePath).addOnSuccessListener(new OnSuccessListener<String>() { //Need to use the driveServiceHelper instance
@Override
public void onSuccess(String s) {
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
});
}

我无法使类 DriveServiceHelper 可序列化并通过意图传递它,并且我不确定我是否可以使函数创建文件静态并从任何地方使用它,因为 DriveServiceHelper 中的 mDriveService 可能为空。

驱动器服务助手:

public class DriveServiceHelper
{
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService)
{
this.mDriveService = mDriveService;
}
public Task<String> createFile(String filePath) {
return Tasks.call(mExecutor, () -> {
String fileId = "------------------------------------";
File gDriveFile = mDriveService.files().get(fileId).execute();
java.io.File fileContent = new java.io.File(filePath);
FileContent mediaContent = new FileContent("text/plain", fileContent);
File fileObjectWithUpdates = new File();
File updatedFile = mDriveService.files().update(gDriveFile.getId(), fileObjectWithUpdates, mediaContent).execute();
if (updatedFile == null) {
throw new IOException("Null result");
}
return updatedFile.getId();

});
}

}

最好的方法是什么?

您是否尝试过将 Drive 对象包装在包装器类中,并使用单例模式在应用程序中的其他位置使用它。类似这个解决方案链接

相关内容

最新更新