2017-08-02 48 views
-1

我需要將視頻的鏈接上傳到谷歌驅動器,以便我可以在網絡瀏覽器中打開視頻,我可以將視頻文件上傳到谷歌驅動器,並可以使用以下代碼獲取文件ID :如何在Android中使用Drive API將上傳文件的網址鏈接到谷歌驅動器?

private void UploadFile(final DriveId driveId) 
{ 
    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() { 
     @Override 
     public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult) 
     { 
      if (!driveContentsResult.getStatus().isSuccess()) 
      { 
       Log.e(TAG, "Error while trying to create new file contents"); 
       return; 
      } 
      OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream(); 
      Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show(); 
      final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv"); 
      try 
      { 
       FileInputStream fileInputStream = new FileInputStream(theFile); 
       byte[] buffer = new byte[1024]; 
       int bytesRead; 
       while ((bytesRead = fileInputStream.read(buffer)) != -1) 
       { 
        outputStream.write(buffer, 0, bytesRead); 
       } 
      } catch (IOException e1) 
      { 
       Log.i(TAG, "Unable to write file contents."); 
      } 
      MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build(); 
      DriveFolder folder = driveId.asDriveFolder(); 
      folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() { 
         @Override 
         public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult) 
         { 
          if (!driveFileResult.getStatus().isSuccess()) 
          { 
           Log.e(TAG, "Error while trying to create the file"); 
           return; 
          } 
          Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId()); 
         } 
        }); 
     } 
    }); 
} 

我嘗試使用下面的代碼來獲取視頻網址:

DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId); 
          DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await(); 
          if (mdRslt != null && mdRslt.getStatus().isSuccess()) { 
           String link = mdRslt.getMetadata().getWebContentLink(); 
           Log.d("LINK", link); 
          } 

但後來我得到了「無法解析符號‘googleApiClient’ 任何建議,請

+2

這是因爲'沒有定義googleApiClient'。您應該像使用代碼中的其他任何地方一樣使用'mGoogleApiClient'。 –

+0

感謝您的重播,但是我注意到我從driveFileResult.getDriveFile()。getDriveId()獲得的文件ID沒有完成:「DriveId:CAESABiwayCK16yy6VAoAA ==」這對我來說很奇怪?如果我有它正確的,那麼我可以通過添加一些字符串開始https://drive.google.com/......文件ID ..... –

+0

這裏是一個線索。您的代碼顯示「上傳到驅動器....」,但您使用的是GDAA,因此您不會上傳到雲端硬盤。你所做的只是在本地保存文件。一段時間後,Play Services會將您的文件同步到雲端硬盤。 – pinoyyid

回答

0

好吧,我?找到了解決方案首先,我必須使用change events listener獲取完整的文件ID,然後我們可以將「drive.google.com/open?id=」添加到文件ID,因此complate url將爲drive.google.com /開?ID =寫到FileID。 這裏就是我的回答:

public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{ 
private static final String TAG = "Google Drive Activity"; 
private static final int REQUEST_CODE_RESOLUTION = 1; 
private static final int REQUEST_CODE_OPENER = 2; 
private GoogleApiClient mGoogleApiClient; 
public DriveFile file; 
private String FOLDER_NAME = "GD_VideoFile"; 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(Drive.API) 
       .addScope(Drive.SCOPE_FILE) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 
    } 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onStop() 
{ 
    super.onStop(); 
    if (mGoogleApiClient != null) { 

     mGoogleApiClient.disconnect(); 
    } 
    super.onPause(); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult result) 
{ 
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); 
    if (!result.hasResolution()) { 

     GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show(); 
     return; 
    } 

    try { 

     result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); 

    } catch (SendIntentException e) { 

     Log.e(TAG, "Exception while starting resolution activity", e); 
    } 
} 

@Override 
public void onConnected(Bundle connectionHint) 
{ 
    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show(); 

    if (mGoogleApiClient != null) 
    { 
     check_folder_exists(); 
    } else 
    { 
     Log.e(TAG, "Could not connect to google drive manager"); 
    } 
} 

@Override 
public void onConnectionSuspended(int cause) 
{ 
    Log.i(TAG, "GoogleApiClient connection suspended"); 
} 

@Override 
protected void onActivityResult(final int requestCode, 
           final int resultCode, final Intent data) 
{ 
    switch (requestCode) 
    { 
     case REQUEST_CODE_OPENER: 
      if (resultCode == RESULT_OK) 
      { 
       DriveId mFileId = data.getParcelableExtra(
         OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID); 
       Log.e("file id", mFileId.getResourceId() + ""); 
       String url = "https://drive.google.com/open?id="+ mFileId.getResourceId(); 
       Intent i = new Intent(Intent.ACTION_VIEW); 
       i.setData(Uri.parse(url)); 
       startActivity(i); 
      } 
      break; 
     default: 
      super.onActivityResult(requestCode, resultCode, data); 
      break; 
    } 
} 

private void check_folder_exists() 
{ 
    Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build(); 
    Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() { 
     @Override 
     public void onResult(@NonNull DriveApi.MetadataBufferResult result) 
     { 
      if (!result.getStatus().isSuccess()) 
      { 
       Log.e(TAG, "Cannot create folder in the root."); 
      } else 
      { 
       boolean isFound = false; 
       for (Metadata m : result.getMetadataBuffer()) 
       { 
        if (m.getTitle().equals(FOLDER_NAME)) { 
         Log.e(TAG, "Folder exists"); 
         isFound = true; 
         DriveId driveId = m.getDriveId(); 
         UploadFile(driveId); 
         break; 
        } 
       } 
       if (!isFound) 
       { 
        Log.i(TAG, "Folder not found; creating it."); 
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build(); 
        Drive.DriveApi.getRootFolder(mGoogleApiClient) 
          .createFolder(mGoogleApiClient, changeSet) 
          .setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() { 
           @Override 
           public void onResult(@NonNull DriveFolder.DriveFolderResult result) 
           { 
            if (!result.getStatus().isSuccess()) 
            { 
             Log.e(TAG, "Error while trying to create the folder"); 
            } else { 
             Log.i(TAG, "Created a folder"); 
             DriveId driveId = result.getDriveFolder().getDriveId(); 
             UploadFile(driveId); 
            } 
           } 
          }); 
       } 
      } 
     } 
    }); 
} 


private void UploadFile(final DriveId driveId) 
{ 

    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() 
    { 
     @Override 
     public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult) 
     { 
      if (!driveContentsResult.getStatus().isSuccess()) 
      { 
       Log.e(TAG, "U AR A MORON! Error while trying to create new file contents"); 
       return; 
      } 

      OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream(); 
      Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show(); 
      final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov"); 
      try 
      { 
       FileInputStream fileInputStream = new FileInputStream(theFile); 
       byte[] buffer = new byte[1024]; 
       int bytesRead; 
       while ((bytesRead = fileInputStream.read(buffer)) != -1) 
       { 
        outputStream.write(buffer, 0, bytesRead); 
       } 
      } catch (IOException e1) 
      { 
       Log.i(TAG, "Unable to write file contents."); 
      } 

      MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build(); 
      DriveFolder folder = driveId.asDriveFolder(); 
      folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() 
      { 
         @Override 
         public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult) 
         { 
          if (!driveFileResult.getStatus().isSuccess()) 
          { 
           Log.e(TAG, "Error while trying to create the file"); 
           return; 
          } 
          Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show(); 

          String Folder_Id = driveId.getResourceId(); 
          System.out.println("The folder id: " +Folder_Id); 

          //This is to get the file id from the listener 
          DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId(); 
          DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id); 
          file.addChangeListener(mGoogleApiClient, changeListener); 
         } 

       //A listener to handle file change events. 
       final private ChangeListener changeListener = new ChangeListener() 
       { 
        @Override 
        public void onChange(ChangeEvent event) 
        { 
         String File_Completed_Id = event.getDriveId().getResourceId(); 
         System.out.println("The uploaded file id: " +File_Completed_Id); 
         System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id); 

        } 
       }; 
      } 
        ); 
     } 

    } 
    ); 
} 

}

相關問題