如何在Android的Google云端硬盘中保存任何类型的文件?

时间:2019-02-20 18:50:11

标签: android google-drive-api mime

我需要从手机中选择几种类型的文件,并且需要上传到Google驱动器。我可以为图像文件执行此操作,但不能为其他MIME类型(例如PDF或txt文件)执行此操作。

我可以选择它。但是在createFileIntentSender()方法中,我只能传递位图。

我拥有的代码:

 private void showFileChooser() {
//        Intent intent = new Intent();
//        intent.setType("image/*|application/pdf|audio/*");
//        intent.setAction(Intent.ACTION_GET_CONTENT);
//        startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_REQUEST);

        String[] mimeTypes =
                {"image/*","application/pdf","application/msword","application/vnd.ms-powerpoint","application/vnd.ms-excel","text/plain"};

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
            if (mimeTypes.length > 0) {
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            }
        } else {
            String mimeTypesStr = "";
            for (String mimeType : mimeTypes) {
                mimeTypesStr += mimeType + "|";
            }
            intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
        }
        startActivityForResult(Intent.createChooser(intent,"ChooseFile"), PICK_IMAGE_REQUEST);
    }

    //handling the image chooser activity result
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            int random = new Random().nextInt(1000006) + 20;
//            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "attach_" + random ;
            filename = imageFileName;
            Uri returnUri = data.getData();
            String mimeType = getActivity().getContentResolver().getType(returnUri);
            Log.d("Testing", "mime type :::  " +mimeType);
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
                Log.d("Testing", "bitmap Excep:::  " +bitmap);
                saveFileToDrive(mimeType);
//                imageViewuri.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == REQUEST_CODE_CREATOR && resultCode == RESULT_OK ) {
            /// filePath = data.getData();
            // try {
//            Log.e("drive res",data.getDataString());
            /*} catch (IOException e) {
                e.printStackTrace();
            }*/


             driveId =
                    data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
            String s = driveId.encodeToString();
            String s1 = s.substring(s.indexOf(":")+1);
            s1.trim();
            mStrDeviceID.add(s1);

            mTvAttchment.setVisibility(View.VISIBLE);
            mTvAttchment.setText(mTvAttchment.getText()+"\n"+filename);

            Log.d("Testing", "File created with ID: " + driveId.encodeToString()+"  "+filename);
            //showMessage(getString(R.string.file_created, "File created with ID: " + driveId));
        }
    }

    /** Create a new file and save it to Drive. */
    private void saveFileToDrive(final String mime) {
        // Start by creating a new contents, and setting a callback.
        //  Log.i(TAG, "Creating new contents.");
        // final Bitmap image = mBitmapToSave;
        Log.d("Testing", "last signed account:: "+GoogleSignIn.getLastSignedInAccount(getActivity().getApplicationContext()));
        mDriveClient = Drive.getDriveClient(getActivity().getApplicationContext(), GoogleSignIn.getLastSignedInAccount(getActivity().getApplicationContext()));
        // Build a drive resource client.
        mDriveResourceClient =
                Drive.getDriveResourceClient(getActivity().getApplicationContext(), GoogleSignIn.getLastSignedInAccount(getActivity().getApplicationContext()));

        Log.d("Testing", "inside saveFileToDrive:::  ");
        mDriveResourceClient
                .createContents()
                .continueWithTask(
                        new Continuation<DriveContents, Task<Void>>() {
                            @Override
                            public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception {
                                Log.d("Testing", "inside then method:::  ");
                                return createFileIntentSender(task.getResult(), bitmap, mime);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // Log.w(TAG, "Failed to create new contents.", e);
                            }
                        });
    }


    private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image, String mimetype) {
        //Log.i(TAG, "New contents created.");
        // Get an output stream for the contents.

        Log.d("Testing", "inside createFileIntentSender:::  ");
        OutputStream outputStream = driveContents.getOutputStream();
        // Write the bitmap data from it.
        ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
        Log.d("Testing", "inside createFileIntentSender 2222:::  ");
        try {
            outputStream.write(bitmapStream.toByteArray());
        } catch (IOException e) {
            /// Log.w(TAG, "Unable to write file contents.", e);
            Log.d("Testing", "inside createFileIntentSender 333:::  "+e.getMessage());
        }

        //  DriveId btd = new DriveId();

        // Create the initial metadata - MIME type and title.
        // Note that the user will be able to change the title later.
        MetadataChangeSet metadataChangeSet =
                new MetadataChangeSet.Builder()
                        .setMimeType(mimetype)
                        .setTitle(filename)
                        .build();
        //filename = "sample"+mimetype;
        // Set up options to configure and display the create file activity.
        CreateFileActivityOptions createFileActivityOptions =
                new CreateFileActivityOptions.Builder()
                        .setInitialMetadata(metadataChangeSet)
                        .setInitialDriveContents(driveContents)
                        .build();

        return mDriveClient
                .newCreateFileActivityIntentSender(createFileActivityOptions)
                .continueWith(
                        new Continuation<IntentSender, Void>() {
                            @Override
                            public Void then(@NonNull Task<IntentSender> task) throws Exception {
                                Log.d("Testing", "inside then:::  ");
                                startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0, Bundle.EMPTY);
                                return null;
                            }
                        });
    }

0 个答案:

没有答案
相关问题