gpt4 book ai didi

android - 如何设置 GoogleAccountCredential 的 setSelectedAccountName?用于在 YouTube 上上传视频

转载 作者:太空狗 更新时间:2023-10-29 14:07:36 28 4
gpt4 key购买 nike

实际上,我最近 4 天尝试在 YouTube 上上传视频。有一些限制:-

1- 设备中将没有 google play 服务。

2- 也没有 google plus。

3- 也没有任何 Gmail 帐户,也没有添加 Google 帐户的选项。

我已经问过了

How to upload video from android app using youtube API V3?

但是到现在都无法破解

我做了什么:-

1- 我已经通过使用 google post 获得了 OAuth2

https://developers.google.com/identity/protocols/OAuth2InstalledApp

我也得到了acces_token。

我得到了用户邮件 ID,现在我想为 Youtube 设置 GoogleAccountCredential 的 setSelectedAccountName。代码如下:

private static final String TAG = "MainActivity";

public static final String DEVELOPER_KEY = "AIzaSyD4KOe1HZyEE70ripFJRLqxrHHQVeyEVVk";

// CLIENT_ID == Google APIs Console Project Number:
public static final String CLIENT_ID = "872271412588-uor5rjlcv0o5nc0f0uqlap3k0pbofp9n.apps.googleusercontent.com";

public static final String SCOPE = "email%20profile";//"https://www.googleapis.com/auth/youtube.upload";

private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth?";
private static final String CALLBACK_URL = "http%3A%2F%2Flocalhost%2Foauth2callback";
private static final String RESPONSE_TYPE = "code";


private static final int CAPTURE_RETURN = 1;
private static final int GALLERY_RETURN = 2;
private static final int SUBMIT_RETURN = 3;

private ProgressBar progressBar;

private Button btnCaptureVideo;
private Button btnSelectFromGallery;
private YouTube youtube;
private GoogleAccountCredential credential;
private static final String PREF_ACCOUNT_NAME = "accountName";
/**
* Global instance of the HTTP transport.
*/
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY = new GsonFactory();
public static final String VIDEO_FILE_FORMAT = "MP4";
private static final int REQUEST_ACCOUNT_PICKER = 2;
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_AUTHORIZATION = 1;
private Button mBtnUploadVideo;
private LinearLayout mWebViewContainer, mViewContainer;
private WebView mWebView;
public static final String[] SCOPES = {Scopes.PROFILE, YouTubeScopes.YOUTUBE_UPLOAD, YouTubeScopes.YOUTUBEPARTNER, YouTubeScopes.YOUTUBE};
private IntentFilter intentFilter;
private boolean isReceiverRegistered;
private ProgressDialog mProgressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name = AccountManager.KEY_ACCOUNT_NAME;

credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(SCOPE));
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
//credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

Log.i("MainActivity", credential.toString());
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
"YouTubeUploadVideo").build();
Log.i("MainActivity", youtube.toString());
/* try {
//String token = credential.getToken();
//Log.i(TAG, token);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
Log.i(TAG, e.getMessage());
e.printStackTrace();
}*/

mBtnUploadVideo = (Button) findViewById(R.id.btnUploadVideo);
mBtnUploadVideo.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, AuthorizeToUser.class);
startActivityForResult(intent, 1001);

}
});

intentFilter = new IntentFilter();
intentFilter.addAction("com.example.gur38618.youtubeuploadvideo.GET_USER_INFO");
intentFilter.addAction("com.example.gur38618.youtubeuploadvideo.PROFILE_ME");
registerReceiver();
mProgressDialog = new ProgressDialog(this);

}

private void uploadVideo() {
YouTube.Videos.Insert videoInsert = prepareUpload(new File("/sdcard/img/test.mp4"));

new VideoUploadAsyncTask(this).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, videoInsert);
Log.i(TAG, "done");
}

public YouTube.Videos.Insert prepareUpload(File videoFile) {

try {
Video videoObjectDefiningMetadata = new Video();

VideoStatus status = new VideoStatus();
status.setPrivacyStatus("public");
videoObjectDefiningMetadata.setStatus(status);

VideoSnippet snippet = new VideoSnippet();

snippet.setTitle(videoFile.getName());
snippet.setDescription("Uploaded via SKT Android app");

List<String> tags = new ArrayList<String>();
tags.add("SKT");
snippet.setTags(tags);

videoObjectDefiningMetadata.setSnippet(snippet);

InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(videoFile)));
mediaContent.setLength(videoFile.length());
Log.i(TAG + " Length ", "" + videoFile.length());
YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,status", videoObjectDefiningMetadata, mediaContent);

MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

uploader.setDirectUploadEnabled(false);

uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);

return videoInsert;

} catch (FileNotFoundException e) {
Log.i(TAG, e.getMessage());
return null;
} catch (IOException e) {
Log.i(TAG, e.getMessage());
return null;
}

}

public class VideoUploadAsyncTask extends AsyncTask<YouTube.Videos.Insert, Void, String> {

public VideoUploadAsyncTask(Activity activity) {

}

@Override
protected String doInBackground(YouTube.Videos.Insert... params) {
Log.i(TAG, "Starting...");
try {

YouTube.Videos.Insert videoInsert = params[0];
//I have got exception user acocount should not be null
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {

switch (uploader.getUploadState()) {
case INITIATION_STARTED:
Log.d(TAG, "# INITIATION_STARTED ");
break;

case INITIATION_COMPLETE:
Log.d(TAG, "# INITIATION_COMPLETE ");
break;

case MEDIA_IN_PROGRESS:
int progress = (int) Math.round(uploader.getProgress() * 100);
Log.d(TAG, "# MEDIA_IN_PROGRESS : progress = " + progress + "%");

//publishProgress(progress);
break;

case MEDIA_COMPLETE:
Log.d(TAG, "# MEDIA_COMPLETE ");
// publishProgress(100);
break;

case NOT_STARTED:
Log.d(TAG, "# NOT_STARTED ");
break;

default:
break;
}
}
};

uploader.setProgressListener(progressListener);

Video returnedVideo = videoInsert.execute();

return returnedVideo.getId();

} catch (GooglePlayServicesAvailabilityIOException gpsaioe) {

} catch (UserRecoverableAuthIOException uraioe) {

} catch (GoogleAuthIOException gaioe) {

} catch (IOException ioe) {

}
return null;
}
}

public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// I got mail id here
credential.setSelectedAccountName("app@gmail.com");//here I put mail id
credential.setBackOff(new ExponentialBackOff());
uploadVideo();
}
}
};

Aboe代码为问题描述的部分代码。

我已经导入了:-

导入 com.google.api.services.youtube.YouTubeScopes;

导入 com.google.api.client.http.HttpTransport;

导入 com.google.api.client.json.gson.GsonFactory;

这是崩溃日志:-

    07-30 00:52:41.702    1958-2757/com.example.gur38618.youtubeuploadvideo E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.IllegalArgumentException: the name must not be empty: null
at android.accounts.Account.<init>(Account.java:48)
at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:255)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:279)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequest(MediaHttpUploader.java:562)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeUploadInitiation(MediaHttpUploader.java:519)
at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:384)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:427)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.gur38618.youtubeuploadvideo.MainActivity$VideoUploadAsyncTask.doInBackground(MainActivity.java:261)
at com.example.gur38618.youtubeuploadvideo.MainActivity$VideoUploadAsyncTask.doInBackground(MainActivity.java:208)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)

任何帮助都是非常宝贵的。

最佳答案

我通过设置 set selectedaccount 而不是 setselectedAccountName 解决了这个问题,

credential = GoogleAccountCredential.usingOAuth2(context, scopes);
credential.setSelectedAccount(new Account("userEmail@gmail.com", "com.yourpakage.name"));

关于android - 如何设置 GoogleAccountCredential 的 setSelectedAccountName?用于在 YouTube 上上传视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31705404/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com