如何修复‘Drive.API已弃用’的警告?
解决GoogleApiClient弃用警告的方案
嘿,这个问题我之前也碰到过!GoogleApiClient确实在几年前就被官方弃用了,现在Google推荐使用更轻量化、模块化的API来替代,下面是具体的重构步骤:
1. 先更新依赖版本
你当前用的15.0.0版本非常老旧,建议升级到最新的稳定版(可以去Google Maven仓库查询最新版本号,比如目前常用的是20.7.0左右),更新后的依赖配置如下:
implementation 'com.google.android.gms:play-services-auth:20.7.0' implementation 'com.google.android.gms:play-services-drive:20.7.0'
2. 替换GoogleApiClient为模块化API
原来的GoogleApiClient把多个API打包在一起,现在拆分后,我们需要分别处理Google登录和Drive服务:
第一步:创建GoogleSignInClient(替代登录相关的GoogleApiClient逻辑)
首先配置GoogleSignInOptions,包含Drive所需的权限,然后构建GoogleSignInClient:
// 配置登录选项,包含Drive所需的权限 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(new Scope(Drive.SCOPE_FILE)) .requestEmail() .build(); // 创建GoogleSignInClient GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
第二步:启动登录流程,获取用户账户
原来的enableAutoManage自动连接逻辑需要替换为主动启动登录意图,在Activity中触发登录:
// 自定义请求码,比如1001 private static final int REQUEST_CODE_SIGN_IN = 1001; // 启动登录界面 Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN);
然后在onActivityResult中处理登录结果(如果使用的是AndroidX的Activity Result API,也可以用registerForActivityResult实现):
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // 登录成功,获取用户账户 GoogleSignInAccount account = task.getResult(ApiException.class); // 用这个账户初始化Drive客户端 initDriveClient(account); } catch (ApiException e) { // 处理登录失败的情况 Log.e(TAG, "登录失败: " + e.getStatusCode()); } } }
第三步:初始化Drive客户端
登录成功后,用获取到的GoogleSignInAccount来初始化Drive的两个核心客户端:
private DriveClient mDriveClient; private DriveResourceClient mDriveResourceClient; private void initDriveClient(GoogleSignInAccount account) { mDriveClient = Drive.getDriveClient(getApplicationContext(), account); mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), account); // 这里可以执行Drive相关的操作,比如获取根目录 mDriveResourceClient.getRootFolder() .addOnSuccessListener(rootFolder -> { // 成功获取根目录,执行后续操作 }) .addOnFailureListener(e -> { // 处理操作失败的情况 }); }
3. 关键变化说明
- 不再需要
GoogleApiClient和enableAutoManage,而是通过GoogleSignInClient处理身份验证,再用验证后的账户初始化Drive客户端 - 新的API采用异步任务(Task)+ 监听器的方式处理结果,替代了原来的连接回调逻辑
- 权限请求更清晰,直接在
GoogleSignInOptions中指定需要的Scope
这样重构后,不仅能消除弃用警告,还能获得更稳定、更符合Google最新规范的实现。
内容的提问来源于stack exchange,提问作者C.B.
相关产品推荐
相关产品推荐

