将视频上传到youtube android
我曾尝试使用以下代码上传视频。但每当我单击“上传”时,它将进入ResumableUpload类的“启动”和“启动”完成。但它没有上传到youtube。我找不到任何异常,也无法理解为什么它没有进入正在进行的媒体 你能帮帮我吗 获取访问令牌并从MainActivity调用uploadservice的代码 MainActivity.java:将视频上传到youtube android,android,oauth-2.0,youtube-data-api,Android,Oauth 2.0,Youtube Data Api,我曾尝试使用以下代码上传视频。但每当我单击“上传”时,它将进入ResumableUpload类的“启动”和“启动”完成。但它没有上传到youtube。我找不到任何异常,也无法理解为什么它没有进入正在进行的媒体 你能帮帮我吗 获取访问令牌并从MainActivity调用uploadservice的代码 MainActivity.java: private void tryAuthenticate() { if (isFinishing()) { return; }
private void tryAuthenticate() {
if (isFinishing()) {
return;
}
mToken = null;
setProgressBarIndeterminateVisibility(true);
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
try {
// Retrieve a token for the given account and scope. It will
// always return either
// a non-empty String or throw an exception.
mToken =
GoogleAuthUtil.getToken(MainActivity.this, mChosenAccountName, "oauth2:"
+ Scopes.PROFILE + " " + YouTubeScopes.YOUTUBE + " "
+ YouTubeScopes.YOUTUBE_UPLOAD);
} catch (GooglePlayServicesAvailabilityException playEx) {
GooglePlayServicesUtil.getErrorDialog(playEx.getConnectionStatusCode(),
MainActivity.this, REQUEST_GMS_ERROR_DIALOG).show();
} catch (UserRecoverableAuthException userAuthEx) {
// Start the user recoverable action using the intent
// returned by
// getIntent()
startActivityForResult(userAuthEx.getIntent(), REQUEST_AUTHENTICATE);
return false;
} catch (IOException transientEx) {
// TODO: backoff
Log.e(this.getClass().getSimpleName(), transientEx.getMessage());
} catch (GoogleAuthException authEx) {
Log.e(this.getClass().getSimpleName(), authEx.getMessage());
}
return true;
}
@Override
protected void onPostExecute(Boolean hideProgressBar) {
invalidateOptionsMenu();
if (hideProgressBar) {
setProgressBarIndeterminateVisibility(false);
}
if (mToken != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
saveAccount();
}
});
}
loadData();
}
};
task.execute((Void) null);
}
public void uploadVideo(View view) {
if (mToken == null) {
return;
}
// if an upload video is selected.
if (mVideoData != null) {
mDirectFragment.directLite(mVideoData, mToken);
mButton.setEnabled(false);
return;
}
// if a video is picked or recorded.
if (mFileURI != null) {
Intent uploadIntent = new Intent(this, UploadService.class);
uploadIntent.setData(mFileURI);
uploadIntent.putExtra(ACCOUNT_KEY, mChosenAccountName);
uploadIntent.putExtra(TOKEN_KEY, mToken);
startService(uploadIntent);
mButton.setEnabled(false);
}
}
}
ResumableUpload.java:
公共级可恢复飞行{
private static int NOTIFICATION_ID = 1001;
private static String VIDEO_FILE_FORMAT = "video/*";
public static String upload(YouTube youtube, final InputStream fileInputStream,
final long fileSize, Context context) {
final NotificationManager mNotifyManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(context.getString(R.string.youtube_upload))
.setContentText(context.getString(R.string.youtube_direct_lite_upload_started))
.setSmallIcon(R.drawable.icon);
String videoId = null;
try {
// Add extra information to the video before uploading.
Video videoObjectDefiningMetadata = new Video();
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();
Calendar cal = Calendar.getInstance();
snippet.setTitle("Test Upload via Java on " + cal.getTime());
snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library "
+ "on " + cal.getTime());
List<String> tags = new ArrayList<String>();
tags.add(Constants.DEFAULT_KEYWORD);
tags.add(Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST));
snippet.setTags(tags);
videoObjectDefiningMetadata.setSnippet(snippet);
InputStreamContent mediaContent =
new InputStreamContent(VIDEO_FILE_FORMAT, new BufferedInputStream(fileInputStream));
mediaContent.setLength(fileSize);
YouTube.Videos.Insert videoInsert =
youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata,
mediaContent);
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
mBuilder.setContentText("Initiation Started").setProgress((int) fileSize,
(int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case INITIATION_COMPLETE:
mBuilder.setContentText("Initiation Completed").setProgress((int) fileSize,
(int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case MEDIA_IN_PROGRESS:
mBuilder
.setContentTitle("YouTube Upload " + (int) (uploader.getProgress() * 100) + "%")
.setContentText("Direct Lite upload in progress")
.setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case MEDIA_COMPLETE:
mBuilder.setContentTitle("YouTube Upload Completed")
.setContentText("Upload complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
case NOT_STARTED:
Log.d(this.getClass().getSimpleName(), "Upload Not Started!");
break;
}
}
};
uploader.setProgressListener(progressListener);
// Execute upload.
Video returnedVideo = videoInsert.execute();
videoId = returnedVideo.getId();
} catch (final GoogleJsonResponseException e) {
if (401 == e.getDetails().getCode()) {
Log.e(ResumableUpload.class.getSimpleName(), e.getMessage());
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
manager.sendBroadcast(new Intent(MainActivity.INVALIDATE_TOKEN_INTENT));
}
} catch (IOException e) {
Log.e("IOException", e.getMessage());
} catch (Throwable t) {
Log.e("Throwable", t.getMessage());
}
return videoId;
}
private static int NOTIFICATION_ID=1001;
私有静态字符串视频文件\u FORMAT=“VIDEO/*”;
公共静态字符串上载(YouTube YouTube,最终输入流文件输入流,
最终长文件大小(上下文){
最终通知经理通知经理=
(NotificationManager)context.getSystemService(context.NOTIFICATION\u服务);
final NotificationCompat.Builder mBuilder=新NotificationCompat.Builder(上下文);
mBuilder.setContentTitle(context.getString(R.string.youtube_上传))
.setContentText(context.getString(R.string.youtube\u direct\u lite\u upload\u start))
.setSmallIcon(R.drawable.icon);
字符串videoId=null;
试一试{
//在上传之前向视频添加额外信息。
视频对象定义元数据=新视频();
VideoStatus状态=新的VideoStatus();
状态。setPrivacyStatus(“公共”);
videoObjectDefiningMetadata.setStatus(状态);
//我们使用VideoSnippet对象设置了大部分元数据。
VideoSnippet snippet=新的VideoSnippet();
Calendar cal=Calendar.getInstance();
setTitle(“在“+cal.getTime()上通过Java测试上传”);
setDescription(“使用Java库通过YouTube数据API V3上传的视频”
+“on”+cal.getTime());
列表标记=新的ArrayList();
tags.add(Constants.DEFAULT\u关键字);
tags.add(Upload.generateKeywordFromplaylID(Constants.Upload_PLAYLIST));
setTags(标签);
videoObjectDefiningMetadata.setSnippet(代码段);
InputStreamContent媒体内容=
新的InputStreamContent(视频文件格式,新的BufferedInputStream(fileInputStream));
setLength(文件大小);
YouTube.Videos.Insert视频插入=
youtube.videos().insert(“代码段、统计信息、状态”),videoObjectDefiningMetadata,
媒体内容);
MediaHttpUploader uploader=videoInsert.getMediaHttpUploader();
uploader.setDirectUploadeEnabled(false);
MediaHttpUploaderProgressListener=新的MediaHttpUploaderProgressListener(){
public void progressChanged(MediaHttpUploader uploader)引发IOException{
开关(uploader.getUploadState()){
案件启动程序已启动:
mBuilder.setContentText(“启动已启动”).setProgress((int)文件大小,
(int)uploader.getNumBytesUploaded(),false);
mNotifyManager.notify(NOTIFICATION_ID,mBuilder.build());
打破
案件启动完成:
mBuilder.setContentText(“初始化完成”).setProgress((int)文件大小,
(int)uploader.getNumBytesUploaded(),false);
mNotifyManager.notify(NOTIFICATION_ID,mBuilder.build());
打破
正在进行的案例媒体:
燃烧炉
.setContentTitle(“YouTube上载”+(int)(uploader.getProgress()*100)+“%”)
.setContentText(“正在进行直接Lite上载”)
.setProgress((int)fileSize,(int)uploader.getNumBytesUploaded(),false);
mNotifyManager.notify(NOTIFICATION_ID,mBuilder.build());
打破
案例媒体完成:
mBuilder.setContentTitle(“YouTube上传完成”)
.setContentText(“上传完成”)
//删除进度条
.setProgress(0,0,false);
mNotifyManager.notify(NOTIFICATION_ID,mBuilder.build());
未启动的案例:
Log.d(this.getClass().getSimpleName(),“上载未启动!”);
打破
}
}
};
setProgressListener(progressListener);
//执行上传。
Video returnedVideo=videoInsert.execute();
videoId=returnedVideo.getId();
}捕获(最终GoogleJsonResponseException e){
如果(401==e.getDetails().getCode()){
Log.e(ResumableUpload.class.getSimpleName(),e.getMessage());
LocalBroadcastManager=LocalBroadcastManager.getInstance(上下文);
manager.sendBroadcast(新意图(MainActivity.INVALIDATE_TOKEN_Intent));
}
}捕获(IOE异常){
Log.e(“IOException”,e.getMessage());
}捕获(可丢弃的t){
Log.e(“Throwable”,t.getMessage());
}
返回videoId;
}
}
private static int NOTIFICATION_ID = 1001;
private static String VIDEO_FILE_FORMAT = "video/*";
public static String upload(YouTube youtube, final InputStream fileInputStream,
final long fileSize, Context context) {
final NotificationManager mNotifyManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(context.getString(R.string.youtube_upload))
.setContentText(context.getString(R.string.youtube_direct_lite_upload_started))
.setSmallIcon(R.drawable.icon);
String videoId = null;
try {
// Add extra information to the video before uploading.
Video videoObjectDefiningMetadata = new Video();
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();
Calendar cal = Calendar.getInstance();
snippet.setTitle("Test Upload via Java on " + cal.getTime());
snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library "
+ "on " + cal.getTime());
List<String> tags = new ArrayList<String>();
tags.add(Constants.DEFAULT_KEYWORD);
tags.add(Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST));
snippet.setTags(tags);
videoObjectDefiningMetadata.setSnippet(snippet);
InputStreamContent mediaContent =
new InputStreamContent(VIDEO_FILE_FORMAT, new BufferedInputStream(fileInputStream));
mediaContent.setLength(fileSize);
YouTube.Videos.Insert videoInsert =
youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata,
mediaContent);
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
mBuilder.setContentText("Initiation Started").setProgress((int) fileSize,
(int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case INITIATION_COMPLETE:
mBuilder.setContentText("Initiation Completed").setProgress((int) fileSize,
(int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case MEDIA_IN_PROGRESS:
mBuilder
.setContentTitle("YouTube Upload " + (int) (uploader.getProgress() * 100) + "%")
.setContentText("Direct Lite upload in progress")
.setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
break;
case MEDIA_COMPLETE:
mBuilder.setContentTitle("YouTube Upload Completed")
.setContentText("Upload complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
case NOT_STARTED:
Log.d(this.getClass().getSimpleName(), "Upload Not Started!");
break;
}
}
};
uploader.setProgressListener(progressListener);
// Execute upload.
Video returnedVideo = videoInsert.execute();
videoId = returnedVideo.getId();
} catch (final GoogleJsonResponseException e) {
if (401 == e.getDetails().getCode()) {
Log.e(ResumableUpload.class.getSimpleName(), e.getMessage());
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
manager.sendBroadcast(new Intent(MainActivity.INVALIDATE_TOKEN_INTENT));
}
} catch (IOException e) {
Log.e("IOException", e.getMessage());
} catch (Throwable t) {
Log.e("Throwable", t.getMessage());
}
return videoId;
}