Created
November 25, 2017 03:21
-
-
Save standinga/9fbbf2681ac86faa581031ef6039b10b to your computer and use it in GitHub Desktop.
Get user's youtube channel id and his youtube subscribtions using Youtube com.google.api.services.youtube.YouTube, no UI.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apply plugin: 'com.android.application' | |
android { | |
compileSdkVersion 26 | |
defaultConfig { | |
applicationId "co.example.youtube" | |
minSdkVersion 19 | |
targetSdkVersion 26 | |
versionCode 1 | |
versionName "1.0" | |
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" | |
} | |
buildTypes { | |
release { | |
minifyEnabled false | |
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' | |
} | |
} | |
} | |
configurations.all { | |
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' | |
} | |
dependencies { | |
implementation fileTree(dir: 'libs', include: ['*.jar']) | |
implementation 'com.android.support:appcompat-v7:26.1.0' | |
implementation 'com.android.support.constraint:constraint-layout:1.0.2' | |
testImplementation 'junit:junit:4.12' | |
compile 'com.google.android.gms:play-services-auth:11.6.0' | |
compile 'com.google.api-client:google-api-client-android:1.22.0' exclude module: 'httpclient' | |
compile 'com.google.apis:google-api-services-youtube:v3-rev182-1.22.0' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package co.example.youtube; | |
/* | |
Example of how to get user's youtube channel id using google OAuth2, | |
the app needs to be registered at: | |
https://console.developers.google.com/apis/ | |
Credentials->Client ID for Android | |
with the same package name (in this case co.example.youtube) | |
otherwise error 10 will be received | |
*/ | |
import android.accounts.Account; | |
import android.content.Intent; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.support.annotation.NonNull; | |
import android.support.v7.app.AppCompatActivity; | |
import android.util.Log; | |
import com.google.android.gms.auth.api.Auth; | |
import com.google.android.gms.auth.api.signin.GoogleSignIn; | |
import com.google.android.gms.auth.api.signin.GoogleSignInAccount; | |
import com.google.android.gms.auth.api.signin.GoogleSignInClient; | |
import com.google.android.gms.auth.api.signin.GoogleSignInOptions; | |
import com.google.android.gms.common.ConnectionResult; | |
import com.google.android.gms.common.api.ApiException; | |
import com.google.android.gms.common.api.GoogleApiClient; | |
import com.google.android.gms.common.api.Scope; | |
import com.google.android.gms.tasks.Task; | |
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.UserRecoverableAuthIOException; | |
import com.google.api.client.http.HttpTransport; | |
import com.google.api.client.json.JsonFactory; | |
import com.google.api.client.json.jackson2.JacksonFactory; | |
import com.google.api.services.youtube.YouTube; | |
import com.google.api.services.youtube.model.Channel; | |
import com.google.api.services.youtube.model.ChannelListResponse; | |
import com.google.api.services.youtube.model.Subscription; | |
import com.google.api.services.youtube.model.SubscriptionListResponse; | |
import java.io.IOException; | |
import java.util.Collections; | |
import java.util.List; | |
/* | |
Example how to obtain logged user's channel id. You need to register youtube api using package name at: | |
*/ | |
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { | |
private static final String TAG = "MainActivity"; | |
// Scope for reading user's contacts | |
private static final String CONTACTS_SCOPE = "https://www.googleapis.com/auth/contacts.readonly"; | |
private static final String YOUTUBE_SCOPE = "https://www.googleapis.com/auth/youtube"; | |
// Bundle key for account object | |
private static final String KEY_ACCOUNT = "key_account"; | |
// Request codes | |
private static final int RC_SIGN_IN = 9001; | |
private static final int RC_RECOVERABLE = 9002; | |
private Account mAccount; | |
private GoogleApiClient mGoogleApiClient; | |
// Global instance of the HTTP transport | |
private static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport(); | |
// Global instance of the JSON factory | |
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); | |
private GoogleSignInClient mGoogleSignInClient; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) | |
.requestScopes(new Scope(CONTACTS_SCOPE), new Scope(YOUTUBE_SCOPE)) | |
.requestEmail() | |
.build(); | |
// Restore instance state | |
if (savedInstanceState != null) { | |
mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT); | |
} | |
mGoogleSignInClient = GoogleSignIn.getClient(this, gso); | |
// Build a GoogleApiClient with access to the Google Sign-In API and the | |
// options specified by gso. | |
mGoogleApiClient = new GoogleApiClient.Builder(this) | |
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) | |
.addApi(Auth.GOOGLE_SIGN_IN_API, gso) | |
.build(); | |
signIn(); | |
} | |
@Override | |
public void onStart() { | |
super.onStart(); | |
// Check if the user is already signed in and all required scopes are granted | |
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); | |
if (GoogleSignIn.hasPermissions(account, new Scope(CONTACTS_SCOPE), new Scope(YOUTUBE_SCOPE))) { | |
Log.d(TAG, "has Permissions"); | |
} else { | |
Log.d(TAG, "NO Permissions"); | |
} | |
} | |
@Override | |
protected void onSaveInstanceState(Bundle outState) { | |
super.onSaveInstanceState(outState); | |
outState.putParcelable(KEY_ACCOUNT, mAccount); | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); | |
if (requestCode == RC_SIGN_IN) { | |
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); | |
handleSignInResult(task); | |
} | |
} | |
private void signIn() { | |
Intent signInIntent = mGoogleSignInClient.getSignInIntent(); | |
startActivityForResult(signInIntent, RC_SIGN_IN); | |
} | |
private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) { | |
Log.d(TAG, "handleSignInResult:" + completedTask.isSuccessful()); | |
try { | |
GoogleSignInAccount account = completedTask.getResult(ApiException.class); | |
// Store the account from the result | |
mAccount = account.getAccount(); | |
// Asynchronously access the Youtube API for the account | |
new GetSubscriptionTask().execute(mAccount); | |
} catch (ApiException e) { | |
Log.w(TAG, "handleSignInResult:error", e); | |
// Clear the local account | |
mAccount = null; | |
} | |
} | |
/** | |
* AsyncTask that uses the credentials from Google Sign In to access Youtube subscription API. | |
*/ | |
private class GetSubscriptionTask extends AsyncTask<Account, Void, List<Subscription>> { | |
@Override | |
protected List<Subscription> doInBackground(Account... params) { | |
try { | |
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( | |
MainActivity.this, | |
Collections.singleton(YOUTUBE_SCOPE)); | |
credential.setSelectedAccount(params[0]); | |
YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) | |
.setApplicationName("Get User's Own Channel") | |
.build(); | |
ChannelListResponse channelListResponse = youtube.channels().list("id,contentDetails") | |
.setMine(true) | |
.setFields("items(contentDetails/relatedPlaylists/uploads,id)") | |
.execute(); | |
// get signed user channel id: | |
Channel myChannel = channelListResponse.getItems().get(0); | |
String channelId = myChannel.getId(); // this is user's channel ID | |
Log.d(TAG, "my youtube channel id: " + channelId); | |
SubscriptionListResponse connectionsResponse = youtube | |
.subscriptions() | |
.list("snippet") | |
.setChannelId(channelId) | |
.execute(); | |
return connectionsResponse.getItems(); | |
} catch (UserRecoverableAuthIOException userRecoverableException) { | |
Log.w(TAG, "getSubscription:recoverable exception", userRecoverableException); | |
startActivityForResult(userRecoverableException.getIntent(), RC_RECOVERABLE); | |
} catch (IOException e) { | |
Log.w(TAG, "getSubscription:exception", e); | |
} | |
return null; | |
} | |
@Override | |
protected void onPostExecute(List<Subscription> subscriptions) { | |
if (subscriptions != null) { | |
Log.d(TAG, "subscriptions : size=" + subscriptions.size()); | |
for (Subscription subscription : subscriptions) { | |
Log.v(TAG, "subscription : " + subscription.getId()); | |
} | |
} else { | |
Log.d(TAG, "subscriptions: null"); | |
} | |
} | |
} | |
// MARK: GoogleApiClient.OnConnectionFailedListener | |
@Override | |
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { | |
// ignore | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah I was struggling too until find out this, Thanks again πππ» ππ»ππ»