首页 > 解决方案 > 使用驱动器 api 将文件或数据库备份到驱动器时​​出错

问题描述

我想将我的应用程序数据库备份到用户的驱动器空间,例如 whatsapp 和大多数应用程序

我用了这段代码

  public void connectToDrive(boolean backup) {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(clscontxt);
        if (account == null){signIn();}
        else {
            toast("already signed");
            mDriveClient = Drive.getDriveClient(clscontxt, account);
            mDriveResourceClient = Drive.getDriveResourceClient(this, account);
            startDriveBackup();
        }
    }
    private void signIn() {
        GoogleSignInClient googlesigninclient = buildgooglesigninclient();
        startActivityForResult(googlesigninclient.getSignInIntent(), 1000);
    }
    private GoogleSignInClient buildgooglesigninclient(){
        GoogleSignInOptions signinoptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestScopes(Drive.SCOPE_FILE)
                        .build();
        return GoogleSignIn.getClient(clscontxt,signinoptions);
    }
    private void startDriveBackup(){
        mDriveResourceClient
                .createContents()
                .continueWithTask(
                        task -> createFileIntentSender(task.getResult()))
                .addOnFailureListener(
                        e -> Log.w(TAG, "Failed to create new contents.", e));
    }
    private Task<Void> createFileIntentSender(DriveContents drivecontents){
        try {
            File dbfile = new File(getDatabasePath(Apconsts.db).toString());
            FileInputStream fis = new FileInputStream(dbfile);
            OutputStream outputStream = drivecontents.getOutputStream();
            outputStream = new FileOutputStream(String.valueOf(drivecontents.getOutputStream()));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) { outputStream.write(buffer, 0, length); }
        } catch (IOException e) { e.printStackTrace(); }
        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                .setTitle("database_backup.db")
                .setMimeType("application/db")
                .build();
        CreateFileActivityOptions createfileactivityoptions = new CreateFileActivityOptions.Builder()
                        .setInitialMetadata(metadataChangeSet)
                        .setInitialDriveContents(drivecontents)
                        .build();
        return mDriveClient
                .newCreateFileActivityIntentSender(createfileactivityoptions)
                .continueWith(
                        task -> {
                            startIntentSenderForResult(task.getResult(), 1001, null, 0, 0, 0);
                            return null;
                        });
    }

经过更多搜索并尝试了很多代码后,它签名正常但不能连续上传并显示此错误

com.google.android.gms.common.api.ApiException: 17: 错误解决被用户取消,原始错误消息:> API_UNAVAILABLE: null

有没有人有同样的问题并且可以解决这个问题?

标签: javaandroidgoogle-api

解决方案


推荐阅读