栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将文件上传到Google云端硬盘?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将文件上传到Google云端硬盘?

可以使用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();   }}

请注意,我使用完整的类名来区分Java文件和驱动器文件。

另请注意,此调用是同步的,因此必须在非UiThread中调用它。

这种方法可以创建文件并将其上传到Google云端硬盘,而无需显示任何选择器对话框,也无需用户交互。

这里有一些文档。

希望这可以帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438753.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号