2017-04-07 89 views
3

我試圖使用以下流程我的應用程序中共享YouTube鏈接:通過YouTube應用上傳視頻並返回視頻鏈接活動

1)使用畫廊挑選意圖從我的應用程序中選擇一個視頻。

2)使用其他意圖將視頻發送到Youtube應用程序,並將其上傳到Youtube。

3)從Youtube應用程序獲取新上傳的視頻鏈接,並通過活動結果將其返回給我的活動。

不幸的是,我被困在第3步,因爲我找不到任何方式來啓動Youtube上傳活動的結果或從中獲得任何鏈接,並且據我所見,目前爲止似乎沒有任何方式將上傳結果返回給調用應用程序。

我知道YouTube的Api存在,但我試圖避免使用它,由於可能出現的使用過度相關的成本。

如果任何人有任何有關如何做到這一點的見解,將不勝感激。

+0

沒有ü解決呢? – Redman

+0

我發現沒有真正的方法可靠地做到這一點,所以我提示用戶在上傳視頻後複製youtube鏈接。當返回到應用程序時,我會自動將剪貼板中的內容複製到UI中,並希望它是正確的鏈接。 – Rakatan

+0

我剛剛找到解決方案,我們可以在成功上傳視頻後獲取視頻id video video = videoInsert.execute();'現在我們可以通過使用 'video.getId();'來獲得id。將此ID附加到'https://www.youtube.com/watch?v ='這是完整的鏈接 – Redman

回答

0

創建類PreferenceManager.java

public class PreferenceManager { 
    static String accountNamem; 

    public static String getAccountName() { 
     return accountNamem; 
    } 

    public static void setAccountName (String accountName) { 
     accountNamem = accountName; 
    } 
} 

創建片段NewUpload.java

import android.accounts.AccountManager; 
import android.app.Activity; 
import android.app.Dialog; 
import android.content.Context; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.provider.MediaStore; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GoogleApiAvailability; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.api.Result; 
import com.google.api.client.extensions.android.http.AndroidHttp; 
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; 
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException; 
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException; 
import com.google.api.client.googleapis.media.MediaHttpUploader; 
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.InputStreamContent; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.gson.GsonFactory; 
import com.google.api.services.youtube.YouTube; 
import com.google.api.services.youtube.YouTubeScopes; 
import com.google.api.services.youtube.model.Video; 
import com.google.api.services.youtube.model.VideoSnippet; 
import com.google.api.services.youtube.model.VideoStatus; 
import com.google.common.collect.Lists; 

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import in.eightfolds.youtubeupload.Utils.PreferenceManager; 

/** 
* Created by Sagar on 21/08/2017. 
*/ 

public class NewUpload extends Fragment{ 

    private static GoogleAccountCredential credential; 
    private static final HttpTransport transport = AndroidHttp.newCompatibleTransport(); 
    private static final JsonFactory jsonFactory = new GsonFactory(); 
    public YouTube youtube; 
    List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_UPLOAD); 
    private static String VIDEO_FILE_FORMAT = "video/*"; 

    static final int REQUEST_GOOGLE_PLAY_SERVICES = 0; 
    static final int REQUEST_AUTHORIZATION = 1; 
    static final int REQUEST_ACCOUNT_PICKER = 2; 
    static Context context; 


    Button btn_upload; 
    private String TAG = "Tag"; 
    private int PLAY_SERVICES_RESOLUTION_REQUEST = 1037; 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     context = getActivity(); 

     return inflater.inflate(R.layout.fragment_upload, container, false); 
    } 

    @Override 
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 
     btn_upload = view.findViewById(R.id.btn_upload); 

    } 

    @Override 
    public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 


     try { 
      credential = googleAccountCredential(scopes); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     youtube = new YouTube.Builder(transport, jsonFactory, credential) 
       .setApplicationName("MyAppName") 
       .build(); 

     btn_upload.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       if (hasPlayServices()) { 
        uploadYouTubeVideos(); 
        Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT).show(); 
       } 
       else { 
        Toast.makeText(getActivity(), "No Play Services", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 
    } 


    private static GoogleAccountCredential googleAccountCredential(List<String> scopes) throws Exception { 

     credential = GoogleAccountCredential.usingOAuth2(context, scopes) 
       .setSelectedAccountName(PreferenceManager.getAccountName()); 
     return credential; 
    } 

    private void chooseAccount() { 
     startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); 
    } 


    public void uploadYouTubeVideos() { 
     if (credential.getSelectedAccountName() == null) { 
      chooseAccount(); 
     } else { 


      File videoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/video.mp4"); 
      YouTube.Videos.Insert videoInsert = prepareUpload(videoFile); 
      new VideoUploadAsyncTask().execute(videoInsert); 
     } 
    } 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     switch (requestCode) { 
      case REQUEST_AUTHORIZATION: 
       if (resultCode == Activity.RESULT_OK) { 
        uploadYouTubeVideos(); 
       } else { 
        chooseAccount(); 
       } 
       break; 
      case REQUEST_ACCOUNT_PICKER: 
       if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) { 
        String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME); 
        if (accountName != null) { 
         credential.setSelectedAccountName(accountName); 
         PreferenceManager.setAccountName(accountName); 

         uploadYouTubeVideos(); 
        } 
       } 
       break; 

     } 
    } 


    public YouTube.Videos.Insert prepareUpload(File videoFile) { 
     try { 
      // Add extra information to the video before uploading. 
      Video videoObjectDefiningMetadata = new Video(); 

      // Set the video to public (default). 
      VideoStatus status = new VideoStatus(); 
      status.setPrivacyStatus("public"); 
      videoObjectDefiningMetadata.setStatus(status); 

      // We set a majority of the metadata with the VideoSnippet object. 
      VideoSnippet snippet = new VideoSnippet(); 

      // Video file name. 
      snippet.setTitle(videoFile.getName()); 
      snippet.setDescription("Test description"); 

      // Set keywords. 
      List<String> tags = new ArrayList<String>(); 
      tags.add("test"); 
      snippet.setTags(tags); 

      // Set completed snippet to the video object. 
      videoObjectDefiningMetadata.setSnippet(snippet); 

      InputStreamContent mediaContent = new InputStreamContent(
        VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(videoFile))); 
      mediaContent.setLength(videoFile.length()); 

      /* 
      * The upload command includes: 1. Information we want returned after file is successfully 
      * uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself. 
      */ 
      YouTube.Videos.Insert videoInsert = youtube.videos() 
        .insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent); 


      // Set the upload type and add event listener. 
      MediaHttpUploader uploader = videoInsert.getMediaHttpUploader(); 

      /* 
      * Sets whether direct media upload is enabled or disabled. True = whole media content is 
      * uploaded in a single request. False (default) = resumable media upload protocol to upload 
      * in data chunks. 
      */ 
      uploader.setDirectUploadEnabled(false); 

      MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { 
       public void progressChanged(MediaHttpUploader uploader) throws IOException { 
        switch (uploader.getUploadState()) { 
         case INITIATION_STARTED: 
          Log.d(TAG, "Upload file: Initiation Started"); 
          break; 
         case INITIATION_COMPLETE: 
          Log.d(TAG, "Upload file: Initiation Completed"); 
          break; 
         case MEDIA_IN_PROGRESS: 
          Log.d(TAG, "Upload file: Upload in progress"); 
          Log.d(TAG, "Upload file: Upload percentage: " + uploader.getProgress()); 
          break; 
         case MEDIA_COMPLETE: 
          Log.d(TAG, "Upload file: Upload Completed!"); 
          break; 
         case NOT_STARTED: 
          Log.d(TAG, "Upload file: Upload Not Started!"); 
          break; 
        } 
       } 
      }; 
      uploader.setProgressListener(progressListener); 

      return videoInsert; 
     } catch (FileNotFoundException e) { 
      Log.e(TAG, "File not found: " + e.getMessage()); 
      return null; 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.getMessage()); 
      return null; 
     } 
    } 


    void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) { 
     getActivity().runOnUiThread(new Runnable() { 
      public void run() { 
       Dialog dialog = 
         GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, getActivity(), 
           REQUEST_GOOGLE_PLAY_SERVICES); 
       dialog.show(); 
      } 
     }); 
    } 



    public class VideoUploadAsyncTask extends AsyncTask<YouTube.Videos.Insert, Void, Void> { 
     @Override 
     protected Void doInBackground(YouTube.Videos.Insert... inserts) { 
      YouTube.Videos.Insert videoInsert = inserts[0]; 
      try { 
       Video returnVideo = videoInsert.execute(); 

       returnVideo.getId(); 
       Log.i("Video Id", "" + returnVideo.getId()); // ----> This is the video Id . 
       Toast.makeText(getActivity(), ""+"https://www.youtube.com/watch?v="+returnVideo.getId(), Toast.LENGTH_SHORT).show(); 
      Log.i("Video Id1", "" + returnVideo.getFileDetails()); 
      Log.i("Video Url", "" + "https://www.youtube.com/watch?v="+returnVideo.getId()); 

      } catch (final GooglePlayServicesAvailabilityIOException availabilityException) { 
       showGooglePlayServicesAvailabilityErrorDialog(
         availabilityException.getConnectionStatusCode()); 
      } catch (UserRecoverableAuthIOException userRecoverableException) { 
       startActivityForResult(
         userRecoverableException.getIntent(), NewUpload.REQUEST_AUTHORIZATION); 
      } catch (IOException e) { 
       Log.e(TAG, "IOException: " + e.getMessage()); 
      } 


      return null; 
     } 
    } 


    private boolean hasPlayServices() { 
     GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); 
     int resultCode = apiAvailability.isGooglePlayServicesAvailable(getActivity()); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (apiAvailability.isUserResolvableError(resultCode)) { 
       apiAvailability.getErrorDialog(getActivity(), resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) 
         .show(); 
      } else { 
       Log.i(TAG, "This device is not supported."); 
//    finish(); 
       Toast.makeText(getActivity(), "Play services not available", Toast.LENGTH_SHORT).show(); 
      } 
      return false; 
     } 
     return true; 
    } 

} 

呼叫使用

NewUpload upload=new NewUpload(); 
    getSupportFragmentManager() 
      .beginTransaction() 
      .add(R.id.relative_main,upload) // give your container Id here 
      .commit(); 

對於上面的例子中,以從活性該片段工作添加讀取存儲權限。保持在內部存儲器中的視頻名稱爲「video.mp4」 - >這部影片將被上傳到已選定的賬戶

您可以在uploadYouTubeVideos()方法來改變內部片段

這個邏輯進行佈局跟上ID 1個按鈕btn_uploadfragment_upload

使用這種依賴於gsonfactory

compile 'com.google.http-client:google-http-client-gson:1.19.0' 
+0

這是基於Youtube Data API的任何機會嗎? – Rakatan

+0

我不確定我是從[這裏](https://stackoverflow.com/questions/18022444/youtube-api-3-upload-video-access-not-configured-android) – Redman

+0

複製大部分'VideoUploadAsyncTask'裏面我們正在得到的網址 – Redman