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

时间:2015-07-29 15:54:49

标签: android youtube youtube-api

其实我正在尝试过去4天在YouTube上传视频。有一些限制: -

1-没有谷歌播放服务将在设备中。

2-没有google plus。

3-没有任何gmail帐户以及&没有添加Google帐户的选项。

我已经提出了一个问题

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

但到现在为止我无法破解它。

我做了什么: -

1-我使用谷歌帖子获得了OAuth2

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

我也得到了access_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)

任何帮助都是非常可取的。

2 个答案:

答案 0 :(得分:1)

我通过设置set selectedaccount而不是setselectedAccountName,

解决了这个问题
credential = GoogleAccountCredential.usingOAuth2(context, scopes);
credential.setSelectedAccount(new Account("userEmail@gmail.com", "com.yourpakage.name"));

答案 1 :(得分:0)

在您的情况下,Android将无法提供帮助,因此您需要执行更多操作like an installed application