可以使用Android版Google Drive REST API(直接使用Google Drive API)而不是Android版Google Drive SDK来实现。
首先,您需要通过选择设备的Google帐户登录Google云端硬盘。我想您已经完成了,因为在Google Drive SDK中还需要登录。要登录,我使用这种依赖性。
compile 'com.google.android.gms:play-services-auth:10.2.0'
然后,要上传文件(通过在REST API中创建文件),请执行以下操作。
首先,导入适用于Android的Google Drive REST API依赖项:
compile('com.google.api-client:google-api-client-android:1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev75-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
其次,创建服务对象以与API连接:
private Drive createService(Context context) {
GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(context.getApplicationContext(), Arrays.asList(new String[]{DriveScopes.DRIVE})).setBackOff(new ExponentialBackOff());
mCredential.setSelectedAccountName("your_logged_account_name");
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.drive.Drive.Builder(
transport, jsonFactory, mCredential)
.setApplicationName(context.getString(R.string.app_name))
.build();
return mService;
}
之后,当您登录并拥有Drive实例(服务)时,可以创建一个文件:
public void uploadFile(java.io.File fileContent) {
try {
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
file.setName("filen_ame");
List<String> parents = new ArrayList<>(1);
parents.add("parent_folder_id"); // Here you need to get the parent folder id
file.setParents(parents);
FileContent mediaContent = new FileContent("your_file_mime_type", fileContent);
mService.files().create(file, mediaContent).setFields("id").execute();
Log.d(TAG, "File uploaded");
} catch (IOException e) {
Log.e(TAG, "Error uploading file: ", e);
e.printStackTrace();
}
}
另请注意,此调用是同步的,因此必须在非UiThread中调用它。
这种方法可以创建文件并将其上传到Google云端硬盘,而无需显示任何选择器对话框,也无需用户交互。
这里有一些文档。
希望这可以帮助。