Repository: Glurt/EdenYouTube Branch: master Commit: f76bdf2768f0 Files: 56 Total size: 81.6 KB Directory structure: gitextract_i78rtbmn/ ├── .gitignore ├── .idea/ │ ├── .name │ ├── compiler.xml │ ├── copyright/ │ │ └── profiles_settings.xml │ ├── gradle.xml │ ├── misc.xml │ ├── modules.xml │ ├── runConfigurations.xml │ └── vcs.xml ├── EdenYouTube.iml ├── README.md ├── app/ │ ├── .gitignore │ ├── app-release.apk │ ├── app.iml │ ├── build.gradle │ ├── fabric.properties │ ├── libs/ │ │ └── YouTubeAndroidPlayerApi.jar │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── eden/ │ │ └── youtubesample/ │ │ └── ApplicationTest.java │ └── main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ └── fonts/ │ │ └── museosans_500.otf │ ├── java/ │ │ └── com/ │ │ └── eden/ │ │ └── youtubesample/ │ │ ├── CustomLightboxActivity.java │ │ ├── CustomYouTubeControlsActivity.java │ │ ├── MainActivity.java │ │ ├── VideoListAdapter.java │ │ ├── VideoListFragment.java │ │ ├── YouTubeActivity.java │ │ ├── YouTubeFragmentActivity.java │ │ ├── content/ │ │ │ └── YouTubeContent.java │ │ └── fragment/ │ │ └── YouTubeFragment.java │ └── res/ │ ├── layout/ │ │ ├── activity_main.xml │ │ ├── activity_youtube.xml │ │ ├── activity_youtube_controls.xml │ │ ├── activity_youtube_fragment.xml │ │ ├── activity_youtube_lightbox.xml │ │ ├── row_layout.xml │ │ └── toolbar.xml │ ├── layout-land/ │ │ └── activity_youtube_controls.xml │ ├── layout-v11/ │ │ └── activity_main.xml │ ├── values/ │ │ ├── apikeys.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ ├── styles.xml │ │ └── typefaces.xml │ ├── values-v11/ │ │ └── styles.xml │ ├── values-v16/ │ │ └── styles.xml │ ├── values-v21/ │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /app/src/release /build ================================================ FILE: .idea/.name ================================================ EdenYouTube ================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/copyright/profiles_settings.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ Android Lint General Maven Abstraction issues 1.8 ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/runConfigurations.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: EdenYouTube.iml ================================================ ================================================ FILE: README.md ================================================ EdenYouTube ------- [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-EdenYouTube-green.svg?style=flat)](https://android-arsenal.com/details/1/2040) The purpose of this repo is to demonstrate the functionality of the [YouTube Library](https://developers.google.com/youtube/android/player/) for Android which acts as an API for the main YouTube application. You can use it as reference for implementing playback functionality within your own application. The app covers everything from popup players:
![YouTubeStandalonePlayer](https://github.com/Glurt/EdenYouTube/blob/master/screenshots/gif1.gif) To embedded players:
![YouTubePlayerView](https://github.com/Glurt/EdenYouTube/blob/master/screenshots/gif2.gif) How to Get ------- You can either clone this repo or download the app from the Play Store:
https://play.google.com/store/apps/details?id=com.eden.youtubesample # Documentation I've written extensively about this application, it's source code and the YouTube API in a blog post that you can find here:
http://createdineden.com/blog/2015/may/12/android-tutorial-how-to-integrate-youtube-videos-into-your-app/ License ------- The MIT License (MIT) Copyright (c) 2015 Scott Cooper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: app/.gitignore ================================================ /src/release /build ================================================ FILE: app/app.iml ================================================ ================================================ FILE: app/build.gradle ================================================ buildscript { repositories { } dependencies { } } apply plugin: 'com.android.application' repositories { } android { compileSdkVersion 23 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.eden.youtubesample" minSdkVersion 8 targetSdkVersion 23 versionCode 5 versionName "1.4" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:support-v4:23.1.1' } ================================================ FILE: app/fabric.properties ================================================ #Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public. #Fri May 01 08:56:57 BST 2015 apiSecret=8faf428a3f12ede6299512a4625ed5cea639c2100a5196e0cfbea5ede22919f3 ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/Scott/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/androidTest/java/com/eden/youtubesample/ApplicationTest.java ================================================ package com.eden.youtubesample; import android.app.Application; import android.test.ApplicationTestCase; /** * Testing Fundamentals */ public class ApplicationTest extends ApplicationTestCase { public ApplicationTest() { super(Application.class); } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/eden/youtubesample/CustomLightboxActivity.java ================================================ package com.eden.youtubesample; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; /*********************************************************************************** * The MIT License (MIT) *

* Copyright (c) 2015 Scott Cooper *

* Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: *

* The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. *

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ /** * This Activity shows how the YouTubePlayerView can be used to create a "Lightbox" similar to that of the * StandaloneYouTubePlayer. Using this method, we can improve upon it by performing transitions and allowing for * custom behaviour, such as closing when the user clicks anywhere outside the player * We manage to avoid rebuffering the video by setting some configchange flags on this activities declaration in the manifest. */ public class CustomLightboxActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { //Keys public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID"; private static final String KEY_VIDEO_TIME = "KEY_VIDEO_TIME"; private YouTubePlayer mPlayer; private boolean isFullscreen; private int millis; private String mVideoId; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_youtube_lightbox); final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout_youtube_activity); relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView); playerView.initialize(getString(R.string.DEVELOPER_KEY), this); if (bundle != null) { millis = bundle.getInt(KEY_VIDEO_TIME); } final Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(KEY_VIDEO_ID)) { mVideoId = extras.getString(KEY_VIDEO_ID); } else { finish(); } } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) { mPlayer = youTubePlayer; youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION); youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI); youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() { @Override public void onFullscreen(boolean b) { isFullscreen = b; } }); if (mVideoId != null && !wasRestored) { youTubePlayer.loadVideo(mVideoId); } if (wasRestored) { youTubePlayer.seekToMillis(millis); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { Toast.makeText(this, "Unable to load video", Toast.LENGTH_LONG).show(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mPlayer != null) { outState.putInt(KEY_VIDEO_TIME, mPlayer.getCurrentTimeMillis()); } } @Override public void onBackPressed() { //If the Player is fullscreen then the transition crashes on L when navigating back to the MainActivity boolean finish = true; try { if (mPlayer != null) { if (isFullscreen) { finish = false; mPlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() { @Override public void onFullscreen(boolean b) { //Wait until we are out of fullscreen before finishing this activity if (!b) { finish(); } } }); mPlayer.setFullscreen(false); } mPlayer.pause(); } } catch (final IllegalStateException e) { e.printStackTrace(); } if (finish) { super.onBackPressed(); } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/CustomYouTubeControlsActivity.java ================================================ package com.eden.youtubesample; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; /*********************************************************************************** * The MIT License (MIT) *

* Copyright (c) 2015 Scott Cooper *

* Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: *

* The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. *

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ public class CustomYouTubeControlsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener { private static final int RECOVERY_DIALOG_REQUEST = 1; public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID"; private YouTubePlayer mPlayer; private String mVideoId; private Button playButton; private Button pauseButton; private RadioGroup styleRadioGroup; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_youtube_controls); final Bundle arguments = getIntent().getExtras(); if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) { mVideoId = arguments.getString(KEY_VIDEO_ID); } final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView); playerView.initialize(getString(R.string.DEVELOPER_KEY), this); playButton = (Button) findViewById(R.id.play_button); playButton.setOnClickListener(this); pauseButton = (Button) findViewById(R.id.pause_button); pauseButton.setOnClickListener(this); styleRadioGroup = (RadioGroup) findViewById(R.id.style_radio_group); ((RadioButton) findViewById(R.id.style_default)).setOnCheckedChangeListener(this); ((RadioButton) findViewById(R.id.style_minimal)).setOnCheckedChangeListener(this); ((RadioButton) findViewById(R.id.style_chromeless)).setOnCheckedChangeListener(this); setControlsEnabled(false); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) { mPlayer = youTubePlayer; if (mVideoId != null) { if (restored) { mPlayer.play(); } else { mPlayer.loadVideo(mVideoId); } } setControlsEnabled(true); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { if (youTubeInitializationResult.isUserRecoverableError()) { youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show(); } else { //Handle the failure Toast.makeText(this, R.string.error_init_failure, Toast.LENGTH_LONG).show(); } } @Override public void onClick(View v) { //Null check the player if (mPlayer != null) { if (v == playButton) { mPlayer.play(); } else if (v == pauseButton) { mPlayer.pause(); } } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked && mPlayer != null) { switch (buttonView.getId()) { case R.id.style_default: mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); break; case R.id.style_minimal: mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); break; case R.id.style_chromeless: mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS); break; } } } private void setControlsEnabled(boolean enabled) { playButton.setEnabled(enabled); pauseButton.setEnabled(enabled); for (int i = 0; i < styleRadioGroup.getChildCount(); i++) { styleRadioGroup.getChildAt(i).setEnabled(enabled); } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/MainActivity.java ================================================ package com.eden.youtubesample; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.google.android.youtube.player.YouTubeApiServiceUtil; import com.google.android.youtube.player.YouTubeInitializationResult; /*********************************************************************************** * The MIT License (MIT) *

* Copyright (c) 2015 Scott Cooper *

* Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: *

* The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. *

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Only add the toolbar if we are on Honeycomb and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } //Check for any issues final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(this); if (result != YouTubeInitializationResult.SUCCESS) { //If there are any issues we can show an error dialog. result.getErrorDialog(this, 0).show(); } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/VideoListAdapter.java ================================================ package com.eden.youtubesample; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; import com.eden.youtubesample.content.YouTubeContent; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubeThumbnailLoader; import com.google.android.youtube.player.YouTubeThumbnailView; import java.util.HashMap; import java.util.Map; /*********************************************************************************** * The MIT License (MIT) *

* Copyright (c) 2015 Scott Cooper *

* Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: *

* The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. *

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ public class VideoListAdapter extends BaseAdapter implements YouTubeThumbnailView.OnInitializedListener { private Context mContext; private Map mLoaders; public VideoListAdapter(final Context context) { mContext = context; mLoaders = new HashMap<>(); } @Override public int getCount() { return YouTubeContent.ITEMS.size(); } @Override public Object getItem(int position) { return YouTubeContent.ITEMS.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { VideoHolder holder; //The item at the current position final YouTubeContent.YouTubeVideo item = YouTubeContent.ITEMS.get(position); if (convertView == null) { //Create the row final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.row_layout, parent, false); //Create the video holder holder = new VideoHolder(); //Set the title holder.title = (TextView) convertView.findViewById(R.id.textView_title); holder.title.setText(item.title); //Initialise the thumbnail holder.thumb = (YouTubeThumbnailView) convertView.findViewById(R.id.imageView_thumbnail); holder.thumb.setTag(item.id); holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this); convertView.setTag(holder); } else { //Create it again holder = (VideoHolder) convertView.getTag(); final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb); if (item != null) { //Set the title holder.title.setText(item.title); //Setting the video id can take a while to actually change the image //in the meantime the old image is shown. //Removing the image will cause the background color to show instead, not ideal //but preferable to flickering images. holder.thumb.setImageBitmap(null); if (loader == null) { //Loader is currently initialising holder.thumb.setTag(item.id); } else { //The loader is already initialised //Note that it's possible to get a DeadObjectException here try { loader.setVideo(item.id); } catch (IllegalStateException exception) { //If the Loader has been released then remove it from the map and re-init mLoaders.remove(holder.thumb); holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this); } } } } return convertView; } @Override public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) { mLoaders.put(view, loader); loader.setVideo((String) view.getTag()); } @Override public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) { final String errorMessage = errorReason.toString(); Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show(); } static class VideoHolder { YouTubeThumbnailView thumb; TextView title; } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/VideoListFragment.java ================================================ package com.eden.youtubesample; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ListView; import com.eden.youtubesample.content.YouTubeContent; import com.eden.youtubesample.fragment.YouTubeFragment; import com.google.android.youtube.player.YouTubeIntents; import com.google.android.youtube.player.YouTubeStandalonePlayer; /*********************************************************************************** * The MIT License (MIT) * Copyright (c) 2015 Scott Cooper * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ public class VideoListFragment extends ListFragment { /** * Empty constructor */ public VideoListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new VideoListAdapter(getActivity())); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { final Context context = getActivity(); final String DEVELOPER_KEY = getString(R.string.DEVELOPER_KEY); final YouTubeContent.YouTubeVideo video = YouTubeContent.ITEMS.get(position); switch (position) { case 0: //Check whether we can actually open YT if (YouTubeIntents.canResolvePlayVideoIntent(context)) { //Opens the video in the YouTube app startActivity(YouTubeIntents.createPlayVideoIntent(context, video.id)); } break; case 1: if (YouTubeIntents.canResolvePlayVideoIntentWithOptions(context)) { //Opens in the YouTube app in fullscreen and returns to this app once the video finishes startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(context, video.id, true, true)); } break; case 2: //Issue #3 - Need to resolve StandalonePlayer as well if (YouTubeIntents.canResolvePlayVideoIntent(context)) { //Opens in the StandAlonePlayer, defaults to fullscreen startActivity(YouTubeStandalonePlayer.createVideoIntent(getActivity(), DEVELOPER_KEY, video.id)); } break; case 3: //Issue #3 - Need to resolve StandalonePlayer as well if (YouTubeIntents.canResolvePlayVideoIntentWithOptions(context)) { //Opens in the StandAlonePlayer but in "Light box" mode startActivity(YouTubeStandalonePlayer.createVideoIntent(getActivity(), DEVELOPER_KEY, video.id, 0, true, true)); } break; case 4: //Opens in the YouTubeSupportFragment final YouTubeFragment fragment = YouTubeFragment.newInstance(video.id); getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit(); break; case 5: //Opens in Custom Activity final Intent fragIntent = new Intent(context, YouTubeFragmentActivity.class); fragIntent.putExtra(YouTubeFragmentActivity.KEY_VIDEO_ID, video.id); startActivity(fragIntent); break; case 6: //Opens in the YouTubePlayerView final Intent actIntent = new Intent(context, YouTubeActivity.class); actIntent.putExtra(YouTubeActivity.KEY_VIDEO_ID, video.id); startActivity(actIntent); break; case 7: //Opens in the the custom Lightbox activity final Intent lightboxIntent = new Intent(context, CustomLightboxActivity.class); lightboxIntent.putExtra(CustomLightboxActivity.KEY_VIDEO_ID, video.id); startActivity(lightboxIntent); break; case 8: //Custom player controls final Intent controlsIntent = new Intent(context, CustomYouTubeControlsActivity.class); controlsIntent.putExtra(CustomLightboxActivity.KEY_VIDEO_ID, video.id); startActivity(controlsIntent); break; } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/YouTubeActivity.java ================================================ package com.eden.youtubesample; import android.os.Bundle; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; /*********************************************************************************** * The MIT License (MIT) * Copyright (c) 2015 Scott Cooper * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ public class YouTubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 1; public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID"; private String mVideoId; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_youtube); final Bundle arguments = getIntent().getExtras(); if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) { mVideoId = arguments.getString(KEY_VIDEO_ID); } final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView); playerView.initialize(getString(R.string.DEVELOPER_KEY), this); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) { //Here we can set some flags on the player //This flag tells the player to switch to landscape when in fullscreen, it will also return to portrait //when leaving fullscreen youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION); //This flag tells the player to automatically enter fullscreen when in landscape. Since we don't have //landscape layout for this activity, this is a good way to allow the user rotate the video player. youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE); //This flag controls the system UI such as the status and navigation bar, hiding and showing them //alongside the player UI youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI); if (mVideoId != null) { if (restored) { youTubePlayer.play(); } else { youTubePlayer.loadVideo(mVideoId); } } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { if (youTubeInitializationResult.isUserRecoverableError()) { youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show(); } else { //Handle the failure Toast.makeText(this, R.string.error_init_failure, Toast.LENGTH_LONG).show(); } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/YouTubeFragmentActivity.java ================================================ package com.eden.youtubesample; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.eden.youtubesample.fragment.YouTubeFragment; /*********************************************************************************** * The MIT License (MIT) * Copyright (c) 2015 Scott Cooper * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ /** * A sample Activity hosting a YouTubeFragment. You could place the Fragment anywhere in the layout. */ public class YouTubeFragmentActivity extends ActionBarActivity { public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_youtube_fragment); final Bundle bundle = getIntent().getExtras(); if (bundle != null && bundle.containsKey(KEY_VIDEO_ID)) { final String videoId = bundle.getString(KEY_VIDEO_ID); final YouTubeFragment fragment = (YouTubeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_youtube); fragment.setVideoId(videoId); } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/content/YouTubeContent.java ================================================ package com.eden.youtubesample.content; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /*********************************************************************************** * The MIT License (MIT) * Copyright (c) 2015 Scott Cooper * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ /** * A Helper class for providing mock data to the app. * In a real world scenario you would either hard code the video ID's in the strings file or * retrieve them from a web service. */ public class YouTubeContent { /** * An array of YouTube videos */ public static List ITEMS = new ArrayList<>(); /** * A map of YouTube videos, by ID. */ public static Map ITEM_MAP = new HashMap<>(); static { addItem(new YouTubeVideo("tttG6SdnCd4", "Open in the YouTube App")); addItem(new YouTubeVideo("x-hH_Txxzls", "Open in the YouTube App in fullscreen")); addItem(new YouTubeVideo("TTh_qYMzSZk", "Open in the Standalone player in fullscreen")); addItem(new YouTubeVideo("tttG6SdnCd4", "Open in the Standalone player in \"Light Box\" mode")); addItem(new YouTubeVideo("x-hH_Txxzls", "Open in the YouTubeFragment")); addItem(new YouTubeVideo("TTh_qYMzSZk", "Hosting the YouTubeFragment in an Activity")); addItem(new YouTubeVideo("tttG6SdnCd4", "Open in the YouTubePlayerView")); addItem(new YouTubeVideo("x-hH_Txxzls", "Custom \"Light Box\" player with fullscreen handling")); addItem(new YouTubeVideo("TTh_qYMzSZk", "Custom player controls")); } private static void addItem(final YouTubeVideo item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } /** * A POJO representing a YouTube video */ public static class YouTubeVideo { public String id; public String title; public YouTubeVideo(String id, String content) { this.id = id; this.title = content; } @Override public String toString() { return title; } } } ================================================ FILE: app/src/main/java/com/eden/youtubesample/fragment/YouTubeFragment.java ================================================ package com.eden.youtubesample.fragment; import android.os.Bundle; import android.widget.Toast; import com.eden.youtubesample.R; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerSupportFragment; /*********************************************************************************** * The MIT License (MIT) * Copyright (c) 2015 Scott Cooper * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ***********************************************************************************/ /** * A sample implementation of a fragment extending YouTubePlayerFragment. * This will take care of most of the work necessary to load and play a video */ public class YouTubeFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 1; private static final String KEY_VIDEO_ID = "KEY_VIDEO_ID"; private String mVideoId; //Empty constructor public YouTubeFragment() { } /** * Returns a new instance of this Fragment * * @param videoId The ID of the video to play */ public static YouTubeFragment newInstance(final String videoId) { final YouTubeFragment youTubeFragment = new YouTubeFragment(); final Bundle bundle = new Bundle(); bundle.putString(KEY_VIDEO_ID, videoId); youTubeFragment.setArguments(bundle); return youTubeFragment; } @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); final Bundle arguments = getArguments(); if (bundle != null && bundle.containsKey(KEY_VIDEO_ID)) { mVideoId = bundle.getString(KEY_VIDEO_ID); } else if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) { mVideoId = arguments.getString(KEY_VIDEO_ID); } initialize(getString(R.string.DEVELOPER_KEY), this); } /** * Set the video id and initialize the player * This can be used when including the Fragment in an XML layout * @param videoId The ID of the video to play */ public void setVideoId(final String videoId) { mVideoId = videoId; initialize(getString(R.string.DEVELOPER_KEY), this); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) { if (mVideoId != null) { if (restored) { youTubePlayer.play(); } else { youTubePlayer.loadVideo(mVideoId); } } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { if (youTubeInitializationResult.isUserRecoverableError()) { youTubeInitializationResult.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show(); } else { //Handle the failure Toast.makeText(getActivity(), R.string.error_init_failure, Toast.LENGTH_LONG).show(); } } @Override public void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putString(KEY_VIDEO_ID, mVideoId); } } ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_youtube.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_youtube_controls.xml ================================================