├── .gitignore
├── .travis.yml
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── flipkart
│ │ └── youtubeviewdemo
│ │ ├── MainActivity.java
│ │ ├── helper
│ │ └── Constants.java
│ │ └── youtubenative
│ │ ├── YouTubeNativeActivityDemo.java
│ │ ├── YouTubeNativeFragmentDemo.java
│ │ └── YouTubePlayerAdapter.java
│ └── res
│ ├── layout
│ ├── activity_main.xml
│ ├── youtube_native_activity_demo.xml
│ ├── youtube_native_fragment.xml
│ └── youtube_player.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── inline-youtube-view
├── .gitignore
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── libs
│ └── YouTubeAndroidPlayerApi-1.2.2.jar
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── flipkart
│ │ └── youtubeview
│ │ ├── YouTubePlayerView.java
│ │ ├── activity
│ │ └── YouTubeActivity.java
│ │ ├── fragment
│ │ ├── YouTubeBaseFragment.java
│ │ ├── YouTubeFragment.java
│ │ └── YouTubeWebViewFragment.java
│ │ ├── listener
│ │ └── YouTubeEventListener.java
│ │ ├── models
│ │ ├── ImageLoader.java
│ │ ├── PlayerStateList.java
│ │ └── YouTubePlayerType.java
│ │ ├── util
│ │ ├── $Precondition$Check.java
│ │ └── ServiceUtil.java
│ │ └── webview
│ │ └── YouTubePlayerWebView.java
│ └── res
│ ├── drawable-hdpi
│ └── play_btn_thumbnail.png
│ ├── drawable-xhdpi
│ └── play_btn_thumbnail.png
│ ├── drawable-xxhdpi
│ └── play_btn_thumbnail.png
│ ├── layout
│ ├── recycler_progressbar.xml
│ ├── video_container.xml
│ ├── youtube_player_view.xml
│ └── youtube_player_web_view.xml
│ └── values
│ ├── color.xml
│ ├── dimens.xml
│ └── strings.xml
├── settings.gradle
├── youtube-activity-android.gif
├── youtube-fragment-android.gif
└── youtube_iframe_player.html
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # Intellij
36 | *.iml
37 | .idea/
38 | .idea/workspace.xml
39 | .idea/tasks.xml
40 | .idea/gradle.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 |
44 | # Keystore files
45 | *.jks
46 |
47 | # External native build folder generated in Android Studio 2.2 and later
48 | .externalNativeBuild
49 |
50 | # Google Services (e.g. APIs or Firebase)
51 | google-services.json
52 |
53 | # Freeline
54 | freeline.py
55 | freeline/
56 | freeline_project_description.json
57 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: true
2 | language: android
3 | jdk:
4 | - oraclejdk8
5 | android:
6 | components:
7 | - tools
8 | - platform-tools
9 | - build-tools-28.0.3
10 | - android-28
11 | - extra-android-support
12 | - extra-android-m2repository
13 | - extra-google-m2repository
14 | script:
15 | - ./gradlew build connectedCheck
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2018 Flipkart Internet Pvt. Ltd. All rights reserved.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Issue Reference
2 | Refer the issue for this change
3 |
4 | Change Summary
5 | A brief description of the change.
6 |
7 | Implementation Summary
8 | A brief but thorough description of the changes put in place to address the issue.
9 |
10 | How to Test
11 | Detailed list of what to test and how to test it. Including all edge cases.
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # inline-youtube-view
2 |
3 | [](https://jitpack.io/#flipkart-incubator/android-inline-youtube-view) [](https://travis-ci.org/flipkart-incubator/android-inline-youtube-view)
4 |
5 | YouTube component for Android, iOS and React. This is a suite of utility libraries around using YouTube inside your [Android](https://github.com/flipkart-incubator/inline-youtube-view/), [iOS](https://github.com/flipkart-incubator/ios-inline-youtube-view/) or React Native app.
6 |
7 | # youtube-android
8 |
9 | Playing Youtube on Android (specially inline) comes with some challenges :
10 | - YouTube SDK does not work on all devices ( where YouTube services could have been uninstalled)
11 | - You cannot run more than one instance of the YouTube view
12 | - Playing them inline where in a list you can have more than one videos in a single list.
13 |
14 | inline-youtube-view for Android checks if the services are available and will fall back gracefully to using WebView in the event they are not.
15 |
16 | YouTubePlayerView : The YouTubePlayerView provided by the YouTube SDK comes with a restriction that the activty hosting this needs to extend from YouTubeBaseActivity. This view removes these restrictions.
17 |
18 | ## Demo Gifs
19 |
20 | ### YouTubePlayer in Activity (Fullscreen Mode)
21 |
22 | 
23 |
24 | ### YouTubePlayer in Fragment (inline native)
25 |
26 | 
27 |
28 | ## How to use ?
29 |
30 | Add it in your root build.gradle at the end of repositories :
31 |
32 | ````java
33 | allprojects {
34 | repositories {
35 | ...
36 | maven { url "https://jitpack.io" }
37 | }
38 | }
39 | ````
40 |
41 | Add the dependency
42 |
43 | ````java
44 | dependencies {
45 | implementation 'com.github.flipkart-incubator:android-inline-youtube-view:1.0.3'
46 | }
47 | ````
48 |
49 | ### YouTubePlayer Activity
50 |
51 | Start an YouTubeActivity intent with apiKey and videoId. This will play the youtube video in a new activity in fullscreen mode.
52 |
53 | ````java
54 | Intent intent = new Intent(MainActivity.this, YouTubeActivity.class);
55 | intent.putExtra("apiKey", Constants.API_KEY);
56 | intent.putExtra("videoId", "3AtDnEC4zak");
57 | startActivity(intent);
58 | ````
59 |
60 | Also, make sure that you add the activity in the AndroidManifest.xml file.
61 |
62 | ````java
63 |
64 | ````
65 |
66 | ### YouTubePlayer Inline
67 |
68 | Create an instance of YouTubePlayerView inside a fragment. To initialize the player, you need to call the initPlayer method with following params:
69 | 1. apiKey
70 | 2. videoId
71 | 3. webviewUrl : the link to iframe.html file (this is required when the device is not able to render native video, a fallback). By default, use 'https://cdn.rawgit.com/flipkart-incubator/inline-youtube-view/60bae1a1/youtube-android/youtube_iframe_player.html'
72 | 4. playerType : native, webview or auto (try native, else fallback to webview)
73 | 5. listener : callback listener
74 | 6. fragment : fragment hosting this view
75 | 7. imageLoader : to load thumbnail image
76 |
77 | ````java
78 | YouTubePlayerView playerView = new YouTubePlayerView(context);
79 | playerView.initPlayer(Constants.API_KEY, videoId, "https://cdn.rawgit.com/flipkart-incubator/inline-youtube-view/60bae1a1/youtube-android/youtube_iframe_player.html", playerType, listener, fragment, imageLoader);
80 |
81 | ````
82 |
83 | ## YouTube iOS Player
84 |
85 | We have open-sourced the inline-youtube-player for [iOS](https://github.com/flipkart-incubator/ios-inline-youtube-view) also.
86 |
87 | ## Contributing
88 |
89 | The easiest way to contribute is by [forking the repo](https://help.github.com/articles/fork-a-repo/), making your changes and [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
90 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | buildToolsVersion '28.0.3'
6 | defaultConfig {
7 | applicationId "com.flipkart.youtubeviewdemo"
8 | minSdkVersion 14
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(dir: 'libs', include: ['*.jar'])
24 | implementation 'com.google.android.material:material:1.1.0-alpha03'
25 | implementation 'androidx.legacy:legacy-support-v4:1.0.0'
26 | implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
27 | implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
28 | implementation 'com.squareup.picasso:picasso:2.5.2'
29 | implementation project(':inline-youtube-view')
30 |
31 | testImplementation 'junit:junit:4.12'
32 | }
33 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/anirudh.r/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flipkart/youtubeviewdemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeviewdemo;
20 |
21 | import android.content.Intent;
22 | import android.os.Bundle;
23 | import androidx.appcompat.app.AppCompatActivity;
24 | import android.view.View;
25 | import android.widget.Button;
26 |
27 | import com.flipkart.youtubeview.activity.YouTubeActivity;
28 | import com.flipkart.youtubeview.models.YouTubePlayerType;
29 | import com.flipkart.youtubeviewdemo.helper.Constants;
30 | import com.flipkart.youtubeviewdemo.youtubenative.YouTubeNativeActivityDemo;
31 |
32 | public class MainActivity extends AppCompatActivity {
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_main);
38 |
39 | Button singleYoutubePlayerButton = findViewById(R.id.singleYoutubePlayer);
40 | Button youtubeNativeFragmentButton = findViewById(R.id.youtubeNativeFragment);
41 | Button youtubeWebViewFragmentButton = findViewById(R.id.youtubeWebviewFragment);
42 |
43 | singleYoutubePlayerButton.setOnClickListener(new View.OnClickListener() {
44 | @Override
45 | public void onClick(View v) {
46 | Intent intent = new Intent(MainActivity.this, YouTubeActivity.class);
47 | intent.putExtra("apiKey", Constants.API_KEY);
48 | intent.putExtra("videoId", "3AtDnEC4zak");
49 | startActivity(intent);
50 | }
51 | });
52 |
53 | youtubeNativeFragmentButton.setOnClickListener(new View.OnClickListener() {
54 | @Override
55 | public void onClick(View v) {
56 | Intent intent = new Intent(MainActivity.this, YouTubeNativeActivityDemo.class);
57 | intent.putExtra("playerType", YouTubePlayerType.STRICT_NATIVE);
58 | startActivity(intent);
59 | }
60 | });
61 |
62 | youtubeWebViewFragmentButton.setOnClickListener(new View.OnClickListener() {
63 | @Override
64 | public void onClick(View v) {
65 | Intent intent = new Intent(MainActivity.this, YouTubeNativeActivityDemo.class);
66 | intent.putExtra("playerType", YouTubePlayerType.WEB_VIEW);
67 | startActivity(intent);
68 | }
69 | });
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flipkart/youtubeviewdemo/helper/Constants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeviewdemo.helper;
20 |
21 | public class Constants {
22 | public static final String API_KEY = "your_api_key";
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flipkart/youtubeviewdemo/youtubenative/YouTubeNativeActivityDemo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeviewdemo.youtubenative;
20 |
21 | import android.os.Bundle;
22 | import androidx.annotation.Nullable;
23 | import androidx.fragment.app.FragmentTransaction;
24 | import androidx.appcompat.app.AppCompatActivity;
25 |
26 | import com.flipkart.youtubeviewdemo.R;
27 |
28 | public class YouTubeNativeActivityDemo extends AppCompatActivity {
29 | @Override
30 | protected void onCreate(@Nullable Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.youtube_native_activity_demo);
33 |
34 | Bundle extras = getIntent().getExtras();
35 |
36 | YouTubeNativeFragmentDemo youTubeNativeFragmentDemo = new YouTubeNativeFragmentDemo();
37 | youTubeNativeFragmentDemo.setArguments(extras);
38 | FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
39 | fragmentTransaction.replace(R.id.container, youTubeNativeFragmentDemo);
40 | fragmentTransaction.commit();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flipkart/youtubeviewdemo/youtubenative/YouTubeNativeFragmentDemo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeviewdemo.youtubenative;
20 |
21 | import android.os.Bundle;
22 | import androidx.annotation.NonNull;
23 | import androidx.annotation.Nullable;
24 | import androidx.fragment.app.Fragment;
25 | import androidx.recyclerview.widget.LinearLayoutManager;
26 | import androidx.recyclerview.widget.RecyclerView;
27 | import android.view.LayoutInflater;
28 | import android.view.View;
29 | import android.view.ViewGroup;
30 |
31 | import com.flipkart.youtubeviewdemo.R;
32 |
33 | import java.util.ArrayList;
34 |
35 | public class YouTubeNativeFragmentDemo extends Fragment {
36 | @Nullable
37 | @Override
38 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
39 | RecyclerView view = (RecyclerView) inflater.inflate(R.layout.youtube_native_fragment, container, false);
40 |
41 | LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
42 | view.setLayoutManager(linearLayoutManager);
43 |
44 | Bundle arguments = getArguments();
45 | int playerType = arguments.getInt("playerType");
46 |
47 | ArrayList videoIds = new ArrayList<>();
48 | videoIds.add("2Vv-BfVoq4g");
49 | videoIds.add("D5drYkLiLI8");
50 | videoIds.add("K0ibBPhiaG0");
51 | videoIds.add("ebXbLfLACGM");
52 | videoIds.add("mWRsgZuwf_8");
53 |
54 | YouTubePlayerAdapter youTubePlayerAdapter = new YouTubePlayerAdapter(videoIds, this, playerType);
55 | view.setAdapter(youTubePlayerAdapter);
56 |
57 | return view;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flipkart/youtubeviewdemo/youtubenative/YouTubePlayerAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeviewdemo.youtubenative;
20 |
21 | import android.view.LayoutInflater;
22 | import android.view.View;
23 | import android.view.ViewGroup;
24 | import android.widget.ImageView;
25 |
26 | import androidx.annotation.NonNull;
27 | import androidx.fragment.app.Fragment;
28 | import androidx.recyclerview.widget.RecyclerView;
29 |
30 | import com.flipkart.youtubeview.YouTubePlayerView;
31 | import com.flipkart.youtubeview.models.ImageLoader;
32 | import com.flipkart.youtubeviewdemo.R;
33 | import com.flipkart.youtubeviewdemo.helper.Constants;
34 | import com.squareup.picasso.Picasso;
35 |
36 | import java.util.ArrayList;
37 |
38 | public class YouTubePlayerAdapter extends RecyclerView.Adapter {
39 |
40 | private ArrayList videoIds;
41 | private Fragment fragment;
42 | private int playerType;
43 |
44 | private ImageLoader imageLoader = new ImageLoader() {
45 | @Override
46 | public void loadImage(@NonNull ImageView imageView, @NonNull String url, int height, int width) {
47 | Picasso.with(imageView.getContext()).load(url).resize(width, height).centerCrop().into(imageView);
48 | }
49 | };
50 |
51 | YouTubePlayerAdapter(ArrayList contents, Fragment fragment, int playerType) {
52 | this.videoIds = contents;
53 | this.fragment = fragment;
54 | this.playerType = playerType;
55 | }
56 |
57 | @Override
58 | public int getItemCount() {
59 | return videoIds.size();
60 | }
61 |
62 | @NonNull
63 | @Override
64 | public YouTubePlayerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
65 | View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_player, parent, false);
66 | return new YouTubePlayerViewHolder(view);
67 | }
68 |
69 | @Override
70 | public int getItemViewType(int position) {
71 | return position;
72 | }
73 |
74 | @Override
75 | public void onBindViewHolder(@NonNull final YouTubePlayerViewHolder holder, int position) {
76 | YouTubePlayerView playerView = holder.playerView;
77 | String videoId = videoIds.get(position);
78 |
79 | playerView.initPlayer(Constants.API_KEY, videoId, "https://cdn.rawgit.com/flipkart-incubator/inline-youtube-view/60bae1a1/youtube-android/youtube_iframe_player.html", playerType, null, fragment, imageLoader);
80 | /*if you want to have your custom icon instead of default icon. Use the below code
81 | and add your own image as below. Make sure to call below method after initPlayer
82 | */
83 | //playerView.overridePlayIcon("https://i.ibb.co/ZKZ2qdc/ic-launcher.png");
84 |
85 | //if you have the resource id then pass it as below
86 | //playerView.overridePlayIcon(R.mipmap.ic_launcher);
87 | }
88 |
89 | static class YouTubePlayerViewHolder extends RecyclerView.ViewHolder {
90 | YouTubePlayerView playerView;
91 |
92 | YouTubePlayerViewHolder(View view) {
93 | super(view);
94 | playerView = view.findViewById(R.id.youtube_player_view);
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
24 |
25 |
32 |
33 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/youtube_native_activity_demo.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/youtube_native_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/youtube_player.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | YouTubeView
3 |
4 |
5 | Hello blank fragment
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | google()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:3.2.1'
10 |
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | google()
20 | maven { url "https://jitpack.io" }
21 | }
22 | }
23 |
24 | task clean(type: Delete) {
25 | delete rootProject.buildDir
26 | }
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Feb 15 22:16:34 IST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/inline-youtube-view/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/inline-youtube-view/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 28
5 | buildToolsVersion '28.0.3'
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | lintOptions {
21 | abortOnError true
22 | }
23 | }
24 |
25 | buildscript {
26 | repositories {
27 | jcenter()
28 | mavenCentral()
29 | google()
30 | }
31 | dependencies {
32 | classpath 'com.android.tools.build:gradle:3.2.1'
33 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
34 | classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.7.5'
35 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
36 | }
37 | }
38 |
39 | allprojects {
40 | repositories {
41 | jcenter()
42 | maven { url "https://plugins.gradle.org/m2/" }
43 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
44 | }
45 | }
46 |
47 | dependencies {
48 | implementation fileTree(include: ['*.jar'], dir: 'libs')
49 | implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
50 | implementation files('libs/YouTubeAndroidPlayerApi-1.2.2.jar')
51 | }
52 |
53 | apply plugin: 'maven-publish'
54 | apply plugin: 'com.github.dcendents.android-maven'
55 |
56 | configurations {
57 | published
58 | }
59 |
60 | task sourceJar(type: Jar) {
61 | from android.sourceSets.main.java.srcDirs
62 | classifier "sources"
63 | }
64 |
65 | configure(install.repositories.mavenInstaller) {
66 | pom.project {
67 | licenses {
68 | license {
69 | name 'The Apache Software License, Version 2.0'
70 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
71 | distribution 'repo'
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/inline-youtube-view/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More d`etails, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/inline-youtube-view/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/inline-youtube-view/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/inline-youtube-view/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jul 17 12:20:00 IST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/inline-youtube-view/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/inline-youtube-view/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/inline-youtube-view/libs/YouTubeAndroidPlayerApi-1.2.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/inline-youtube-view/libs/YouTubeAndroidPlayerApi-1.2.2.jar
--------------------------------------------------------------------------------
/inline-youtube-view/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/anirudh.r/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/YouTubePlayerView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview;
20 |
21 | import android.content.Context;
22 | import android.graphics.PorterDuff;
23 | import android.os.Build;
24 | import android.text.TextUtils;
25 | import android.util.AttributeSet;
26 | import android.view.LayoutInflater;
27 | import android.view.View;
28 | import android.view.ViewGroup;
29 | import android.view.ViewParent;
30 | import android.widget.FrameLayout;
31 | import android.widget.ImageView;
32 | import android.widget.ProgressBar;
33 |
34 | import androidx.annotation.DrawableRes;
35 | import androidx.annotation.MainThread;
36 | import androidx.annotation.NonNull;
37 | import androidx.annotation.Nullable;
38 | import androidx.fragment.app.Fragment;
39 | import androidx.fragment.app.FragmentManager;
40 |
41 | import com.flipkart.youtubeview.fragment.YouTubeBaseFragment;
42 | import com.flipkart.youtubeview.fragment.YouTubeFragment;
43 | import com.flipkart.youtubeview.fragment.YouTubeWebViewFragment;
44 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
45 | import com.flipkart.youtubeview.models.ImageLoader;
46 | import com.flipkart.youtubeview.models.YouTubePlayerType;
47 | import com.flipkart.youtubeview.util.$Precondition$Check;
48 | import com.flipkart.youtubeview.util.ServiceUtil;
49 |
50 | public class YouTubePlayerView extends FrameLayout {
51 |
52 | public static final String TAG = "YouTubeFragmentTAG";
53 | private static final double ASPECT_RATIO = 0.5625; //aspect ratio of player 9:16(height/width)
54 |
55 | protected ImageView playIcon;
56 | @YouTubePlayerType
57 | private int playerType;
58 |
59 | private String videoId;
60 | @Nullable
61 | private YouTubeEventListener listener;
62 | private Fragment fragment;
63 |
64 | private String key;
65 | private FrameLayout playerContainer;
66 | private ImageView thumbnailImageView;
67 | private String webViewUrl;
68 | private ImageLoader imageLoader;
69 |
70 | public YouTubePlayerView(Context context) {
71 | super(context);
72 | init(context);
73 | }
74 |
75 | public YouTubePlayerView(Context context, AttributeSet attrs) {
76 | super(context, attrs);
77 | init(context);
78 | }
79 |
80 | public YouTubePlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
81 | super(context, attrs, defStyleAttr);
82 | init(context);
83 | }
84 |
85 | @Override
86 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
87 | super.onMeasure(widthMeasureSpec, heightMeasureSpec);
88 | int newWidth;
89 | int newHeight;
90 | newWidth = getMeasuredWidth();
91 | newHeight = (int) (newWidth * ASPECT_RATIO);
92 | setMeasuredDimension(newWidth, newHeight);
93 | if (playerContainer != null && playerContainer.getMeasuredHeight() != newHeight) {
94 | ViewGroup.LayoutParams layoutParams = playerContainer.getLayoutParams();
95 | layoutParams.height = newHeight;
96 | playerContainer.setLayoutParams(layoutParams);
97 |
98 | String url = "https://img.youtube.com/vi/" + videoId + "/0.jpg";
99 | if (null != imageLoader) {
100 | imageLoader.loadImage(thumbnailImageView, url, getMeasuredHeight(), getMeasuredWidth());
101 | }
102 | }
103 | }
104 |
105 | @MainThread
106 | public void initPlayer(@NonNull String apiKey, @NonNull String videoId, @Nullable String webViewUrl, @YouTubePlayerType int playerType,
107 | @Nullable YouTubeEventListener listener, @NonNull Fragment fragment, @NonNull ImageLoader imageLoader) {
108 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(apiKey), "apiKey cannot be null");
109 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(videoId), "videoId cannot be null");
110 | //noinspection ConstantConditions
111 | $Precondition$Check.checkArgument(fragment != null, "Fragment cannot be null");
112 | //noinspection ConstantConditions
113 | $Precondition$Check.checkArgument(imageLoader != null, "ImageLoader cannot be null");
114 |
115 | this.key = apiKey;
116 | this.videoId = videoId;
117 | this.webViewUrl = webViewUrl;
118 | this.playerType = playerType;
119 | this.listener = listener;
120 | this.fragment = fragment;
121 | this.imageLoader = imageLoader;
122 | }
123 |
124 | private void init(@NonNull Context context) {
125 | LayoutInflater inflater = LayoutInflater.from(context);
126 | View itemView = inflater.inflate(R.layout.video_container, this, false);
127 | this.addView(itemView);
128 | playerContainer = itemView.findViewById(R.id.youtubeFragmentContainer);
129 | playerContainer.setId(0);
130 | thumbnailImageView = itemView.findViewById(R.id.video_thumbnail_image);
131 | playIcon = itemView.findViewById(R.id.play_btn);
132 | ProgressBar progressBar = itemView.findViewById(R.id.recycler_progressbar);
133 | // For else case there is a layout defined for v21 and above
134 | if (progressBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
135 | int color;
136 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
137 | color = context.getResources().getColor(R.color.default_progress_bar_color, null);
138 | } else {
139 | color = context.getResources().getColor(R.color.default_progress_bar_color);
140 | }
141 | progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
142 | }
143 |
144 | setListeners();
145 | }
146 |
147 | private void setListeners() {
148 | OnClickListener onClickListener = new OnClickListener() {
149 | @Override
150 | public void onClick(View v) {
151 | handleBindPlayer();
152 | }
153 | };
154 |
155 | thumbnailImageView.setOnClickListener(onClickListener);
156 | playIcon.setOnClickListener(onClickListener);
157 | }
158 |
159 | private void handleBindPlayer() {
160 | switch (playerType) {
161 | case YouTubePlayerType.WEB_VIEW:
162 | attachPlayer(false);
163 | break;
164 | case YouTubePlayerType.STRICT_NATIVE:
165 | bindPlayer(false);
166 | break;
167 | case YouTubePlayerType.AUTO:
168 | case YouTubePlayerType.INVALID_VIEW:
169 | default:
170 | bindPlayer(true);
171 | break;
172 | }
173 | }
174 |
175 | private void bindPlayer(boolean auto) {
176 | if (!ServiceUtil.isYouTubeServiceAvailable(getContext())) {
177 | if (!auto && listener != null) {
178 | listener.onNativeNotSupported();
179 | } else {
180 | attachPlayer(false);
181 | }
182 | } else {
183 | attachPlayer(true);
184 | }
185 | }
186 |
187 | private void attachPlayer(boolean isNative) {
188 | if (playerContainer.getId() != R.id.youtubeFragmentContainer) {
189 | YouTubeBaseFragment currentYouTubeFragment = removeCurrentYouTubeFragment();
190 | playerContainer.setId(R.id.youtubeFragmentContainer);
191 | YouTubeBaseFragment youtubePlayerFragment;
192 | if (isNative) {
193 | youtubePlayerFragment = YouTubeFragment.newInstance(key, videoId);
194 | } else {
195 | YouTubeWebViewFragment webViewFragment = YouTubeWebViewFragment.newInstance(webViewUrl, videoId);
196 | if (currentYouTubeFragment instanceof YouTubeWebViewFragment) {
197 | webViewFragment.setWebView(((YouTubeWebViewFragment) currentYouTubeFragment).removeWebView());
198 | }
199 | youtubePlayerFragment = webViewFragment;
200 | }
201 | youtubePlayerFragment.setYouTubeEventListener(listener);
202 | this.fragment.getChildFragmentManager().beginTransaction().add(R.id.youtubeFragmentContainer, (Fragment) youtubePlayerFragment, TAG)
203 | .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
204 | .commit();
205 | }
206 | }
207 |
208 | private YouTubeBaseFragment removeCurrentYouTubeFragment() {
209 | FragmentManager fragmentManager = fragment.getChildFragmentManager();
210 | Fragment youTubeFragment = fragmentManager.findFragmentByTag(TAG);
211 | YouTubeBaseFragment youTubeBaseFragment = null;
212 | if (youTubeFragment instanceof YouTubeBaseFragment) {
213 | youTubeBaseFragment = (YouTubeBaseFragment) youTubeFragment;
214 | View fragmentView = youTubeFragment.getView();
215 | ViewParent parentView = null != fragmentView ? fragmentView.getParent() : null;
216 | youTubeBaseFragment.release();
217 | fragmentManager.beginTransaction().remove(youTubeFragment).commitAllowingStateLoss();
218 | fragmentManager.executePendingTransactions();
219 | if (parentView instanceof View && ((View) parentView).getId() == R.id.youtubeFragmentContainer) {
220 | ((View) parentView).setId(0);
221 | }
222 | }
223 | return youTubeBaseFragment;
224 | }
225 |
226 | public void unbindPlayer() {
227 | if (playerContainer.getId() == R.id.youtubeFragmentContainer) {
228 | removeCurrentYouTubeFragment();
229 | }
230 | }
231 |
232 | @Override
233 | protected void onDetachedFromWindow() {
234 | unbindPlayer();
235 | super.onDetachedFromWindow();
236 | }
237 |
238 | /**
239 | * this function helps to configure the play icon image
240 | *
241 | * @param resId the resource identifier of the drawable
242 | **/
243 | public void overridePlayIcon(@DrawableRes int src) {
244 | if (playIcon != null) {
245 | playIcon.setImageResource(src);
246 | }
247 | }
248 |
249 | /**
250 | * this function helps to configure the play icon image
251 | *
252 | * @param imageUrl the resource identifier of the drawable
253 | **/
254 | public void overridePlayIcon(@NonNull String url) {
255 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(url), "Image Url cannot be null");
256 | $Precondition$Check.checkArgument(!(imageLoader == null),
257 | "Image loader cannot be null. Make sure you have called initPlayer method");
258 | // override play icon
259 | if (playIcon != null) {
260 | int playIconDimen = (int) getContext().getResources().getDimension(R.dimen.play_icon_dimensions);
261 | imageLoader.loadImage(playIcon, url, playIconDimen, playIconDimen);
262 | }
263 | }
264 |
265 | }
266 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/activity/YouTubeActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 |
20 | package com.flipkart.youtubeview.activity;
21 |
22 | import android.graphics.PorterDuff;
23 | import android.os.Build;
24 | import android.os.Bundle;
25 | import androidx.annotation.MainThread;
26 | import androidx.annotation.NonNull;
27 | import androidx.annotation.Nullable;
28 | import android.text.TextUtils;
29 | import android.util.Log;
30 | import android.view.Gravity;
31 | import android.view.ViewGroup;
32 | import android.view.Window;
33 | import android.view.WindowManager;
34 | import android.widget.FrameLayout;
35 | import android.widget.ProgressBar;
36 |
37 | import com.flipkart.youtubeview.R;
38 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
39 | import com.flipkart.youtubeview.models.PlayerStateList;
40 | import com.flipkart.youtubeview.util.$Precondition$Check;
41 | import com.flipkart.youtubeview.util.ServiceUtil;
42 | import com.flipkart.youtubeview.webview.YouTubePlayerWebView;
43 | import com.google.android.youtube.player.YouTubeBaseActivity;
44 | import com.google.android.youtube.player.YouTubeInitializationResult;
45 | import com.google.android.youtube.player.YouTubePlayer;
46 | import com.google.android.youtube.player.YouTubePlayerView;
47 |
48 | import static android.view.View.GONE;
49 | import static android.view.View.VISIBLE;
50 |
51 | public final class YouTubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
52 | /*
53 | * Pass video id as extras
54 | */
55 | public static final String ARG_VIDEO_ID = "videoId";
56 |
57 | /**
58 | * Pass api key as extras
59 | */
60 | public static final String ARG_API_KEY = "apiKey";
61 |
62 | /**
63 | * Pass web-url as extras
64 | */
65 | public static final String ARG_WEB_URL = "webUrl";
66 |
67 | private static final String TAG = "YoutubeActivity";
68 |
69 | @PlayerStateList.PlayerState
70 | private String playerState = PlayerStateList.NONE;
71 |
72 | @Nullable
73 | private YouTubePlayer youTubePlayer;
74 |
75 | @Override
76 | protected void onCreate(Bundle savedInstanceState) {
77 | super.onCreate(savedInstanceState);
78 | setFullscreen();
79 | setContentView(R.layout.youtube_player_view);
80 |
81 | YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player);
82 |
83 | String videoId = getVideoId();
84 | String apiKey = getApiKey();
85 |
86 | /*
87 | * In case videoId or apiKey is null, throw IllegalStateException as apiKey and videoId is mandatory to run
88 | * youtube activity.
89 | */
90 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(videoId), " videoId cannot be null");
91 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(apiKey), " apiKey cannot be null");
92 |
93 | /*
94 | * In case of YouTube Service not available, fallback to WebView implementation.
95 | */
96 | if (ServiceUtil.isYouTubeServiceAvailable(this)) {
97 | youTubePlayerView.initialize(apiKey, this);
98 | } else {
99 | String webViewUrl = getWebUrl();
100 | if (!TextUtils.isEmpty(webViewUrl)) {
101 | youTubePlayerView.setVisibility(GONE);
102 | handleWebViewPlayer(videoId, webViewUrl);
103 | } else {
104 | Log.d(TAG, "Web Url is Null");
105 | finish();
106 | }
107 | }
108 | }
109 |
110 | private void setFullscreen() {
111 | requestWindowFeature(Window.FEATURE_NO_TITLE);
112 | getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
113 | }
114 |
115 | @Nullable
116 | private String getVideoId() {
117 | Bundle extras = null != getIntent() ? getIntent().getExtras() : null;
118 | return null != extras ? extras.getString(ARG_VIDEO_ID) : null;
119 | }
120 |
121 | @Nullable
122 | private String getApiKey() {
123 | Bundle extras = null != getIntent() ? getIntent().getExtras() : null;
124 | return null != extras ? extras.getString(ARG_API_KEY) : null;
125 | }
126 |
127 | @Nullable
128 | private String getWebUrl() {
129 | Bundle extras = null != getIntent() ? getIntent().getExtras() : null;
130 | return null != extras ? extras.getString(ARG_WEB_URL) : null;
131 | }
132 |
133 | private void handleWebViewPlayer(String videoId, String webViewUrl) {
134 | //initialize youtube player webview
135 | YouTubePlayerWebView youTubePlayerWebView = new YouTubePlayerWebView(this);
136 | ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
137 | youTubePlayerWebView.setLayoutParams(layoutParams);
138 |
139 | //initialize progressbar and attach it to the view.
140 | ProgressBar progressBar = initializeProgressBar();
141 | handleProgressBar(progressBar, true);
142 |
143 | FrameLayout.LayoutParams progressBarParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
144 | progressBarParams.gravity = Gravity.CENTER;
145 | youTubePlayerWebView.setBackgroundColor(getResources().getColor(R.color.black));
146 | youTubePlayerWebView.initialize(webViewUrl);
147 |
148 | YouTubeEventListener youTubeEventListener = getYoutubeEventListener(youTubePlayerWebView, progressBar, videoId);
149 | youTubePlayerWebView.setYouTubeListener(youTubeEventListener);
150 |
151 | addContentView(youTubePlayerWebView, layoutParams);
152 | addContentView(progressBar, progressBarParams);
153 | }
154 |
155 | private ProgressBar initializeProgressBar() {
156 | ProgressBar progressBar = new ProgressBar(this);
157 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
158 | int color;
159 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
160 | color = getResources().getColor(R.color.default_progress_bar_color, null);
161 | } else {
162 | color = getResources().getColor(R.color.default_progress_bar_color);
163 | }
164 | progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
165 | }
166 |
167 | return progressBar;
168 | }
169 |
170 | private void handleProgressBar(@NonNull ProgressBar progressBar, boolean show) {
171 | progressBar.setVisibility(show ? VISIBLE : GONE);
172 | }
173 |
174 | @Override
175 | public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean restored) {
176 | youTubePlayer = player;
177 | youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
178 | youTubePlayer.setShowFullscreenButton(true);
179 | youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
180 | youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
181 |
182 | youTubePlayer.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
183 | @Override
184 | public void onPlaying() {
185 | if (youTubePlayer != null && !PlayerStateList.PLAYING.equals(playerState)) {
186 | playerState = PlayerStateList.PLAYING;
187 | }
188 | }
189 |
190 | @Override
191 | public void onPaused() {
192 | handleOnPauseEvent();
193 | }
194 |
195 | @Override
196 | public void onStopped() {
197 | handleStopEvent();
198 | }
199 |
200 | @Override
201 | public void onBuffering(boolean isBuffering) {
202 | //intentionally left blank
203 | }
204 |
205 | @Override
206 | public void onSeekTo(int newPositionMillis) {
207 | handleOnPauseEvent();
208 | }
209 | });
210 |
211 | youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
212 | @Override
213 | public void onLoading() {
214 | //intentionally left blank
215 | }
216 |
217 | @Override
218 | public void onLoaded(String s) {
219 | //intentionally left blank
220 | }
221 |
222 | @Override
223 | public void onAdStarted() {
224 | //intentionally left blank
225 | }
226 |
227 | @Override
228 | public void onVideoStarted() {
229 | //intentionally left blank
230 | }
231 |
232 | @Override
233 | public void onVideoEnded() {
234 | handleStopEvent();
235 | }
236 |
237 | @Override
238 | public void onError(YouTubePlayer.ErrorReason errorReason) {
239 | //intentionally left blank
240 | }
241 | });
242 |
243 | player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
244 | @Override
245 | public void onFullscreen(boolean b) {
246 | handleStopEvent();
247 | }
248 | });
249 |
250 | if (!restored) {
251 | youTubePlayer.loadVideo(getVideoId());
252 | }
253 | }
254 |
255 | private void handleOnPauseEvent() {
256 | if (youTubePlayer != null && (PlayerStateList.PLAYING.equals(playerState))
257 | || PlayerStateList.BUFFERING.equals(playerState)) {
258 | playerState = PlayerStateList.PAUSED;
259 | }
260 | }
261 |
262 | private void handleStopEvent() {
263 | if (youTubePlayer != null && (PlayerStateList.PLAYING.equals(playerState))
264 | || PlayerStateList.BUFFERING.equals(playerState) || PlayerStateList.PAUSED.equals(playerState)) {
265 | playerState = PlayerStateList.STOPPED;
266 | }
267 | }
268 |
269 | private YouTubeEventListener getYoutubeEventListener(@NonNull final YouTubePlayerWebView youTubePlayerWebView,
270 | @NonNull final ProgressBar progressBar,
271 | @NonNull final String videoId) {
272 | return new YouTubeEventListener() {
273 | @Override
274 | @MainThread
275 | public void onReady() {
276 | youTubePlayerWebView.loadVideo(videoId);
277 | handleProgressBar(progressBar, false);
278 | }
279 |
280 | @Override
281 | public void onCued() {
282 | //intentionally left blank
283 | }
284 |
285 | @Override
286 | @MainThread
287 | public void onPlay(int currentTime) {
288 | handleProgressBar(progressBar, false);
289 | }
290 |
291 | @Override
292 | @MainThread
293 | public void onPause(int currentTime) {
294 | //intentionally left blank
295 | }
296 |
297 | @Override
298 | @MainThread
299 | public void onStop(int currentTime, int totalDuration) {
300 | //intentionally left blank
301 | }
302 |
303 | @Override
304 | @MainThread
305 | public void onBuffering(int currentTime, boolean isBuffering) {
306 | //intentionally left blank
307 | }
308 |
309 | @Override
310 | @MainThread
311 | public void onSeekTo(int currentTime, int newPositionMillis) {
312 | //intentionally left blank
313 | }
314 |
315 | @Override
316 | @MainThread
317 | public void onInitializationFailure(String error) {
318 | //intentionally left blank
319 | }
320 |
321 | @Override
322 | @MainThread
323 | public void onNativeNotSupported() {
324 | //intentionally left blank
325 | }
326 | };
327 | }
328 |
329 | @Override
330 | public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
331 | this.youTubePlayer = null;
332 | }
333 |
334 | @Override
335 | public void onStop() {
336 | super.onStop();
337 | handleStopEvent();
338 | }
339 |
340 | @Override
341 | public void onBackPressed() {
342 | finish();
343 | }
344 |
345 | @Override
346 | public void onDestroy() {
347 | super.onDestroy();
348 | if (youTubePlayer != null) {
349 | youTubePlayer.release();
350 | }
351 | }
352 | }
353 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/fragment/YouTubeBaseFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.fragment;
20 |
21 | import androidx.annotation.Nullable;
22 |
23 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
24 |
25 | public interface YouTubeBaseFragment {
26 |
27 | void setYouTubeEventListener(@Nullable YouTubeEventListener listener);
28 |
29 | void release();
30 | }
31 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/fragment/YouTubeFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.fragment;
20 |
21 | import android.os.Bundle;
22 | import androidx.annotation.MainThread;
23 | import androidx.annotation.NonNull;
24 | import androidx.annotation.Nullable;
25 | import android.text.TextUtils;
26 |
27 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
28 | import com.flipkart.youtubeview.models.PlayerStateList;
29 | import com.flipkart.youtubeview.util.$Precondition$Check;
30 | import com.google.android.youtube.player.YouTubeInitializationResult;
31 | import com.google.android.youtube.player.YouTubePlayer;
32 | import com.google.android.youtube.player.YouTubePlayerSupportFragment;
33 |
34 | public final class YouTubeFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener, YouTubeBaseFragment {
35 |
36 | private static final String ARG_VIDEO_ID = "videoId";
37 | private static final String ARG_API_KEY = "apiKey";
38 |
39 | @PlayerStateList.PlayerState
40 | private String playerState = PlayerStateList.NONE;
41 | @Nullable
42 | private YouTubeEventListener listener;
43 | @Nullable
44 | private YouTubePlayer youTubePlayer;
45 |
46 | public static YouTubeFragment newInstance(@NonNull String apiKey, @NonNull final String videoId) {
47 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(apiKey), "apiKey cannot be null");
48 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(videoId), "videoId cannot be null");
49 | YouTubeFragment fragment = new YouTubeFragment();
50 | Bundle bundle = new Bundle();
51 | bundle.putString(ARG_VIDEO_ID, videoId);
52 | bundle.putString(ARG_API_KEY, apiKey);
53 | fragment.setArguments(bundle);
54 | return fragment;
55 | }
56 |
57 | @Override
58 | public void setYouTubeEventListener(@Nullable YouTubeEventListener listener) {
59 | this.listener = listener;
60 | }
61 |
62 | @Override
63 | public void onSaveInstanceState(Bundle outState) {
64 | /* release youTubePlayer when home button pressed. */
65 | release();
66 | super.onSaveInstanceState(outState);
67 | }
68 |
69 | @Override
70 | public void onStart() {
71 | super.onStart();
72 | if (null == youTubePlayer) {
73 | Bundle arguments = getArguments();
74 | if (null != arguments) {
75 | initialize(arguments.getString(ARG_API_KEY), this);
76 | }
77 | }
78 | }
79 |
80 | @Override
81 | public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean restored) {
82 | youTubePlayer = player;
83 | youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
84 | youTubePlayer.setShowFullscreenButton(false);
85 |
86 | if (listener != null) {
87 | listener.onReady();
88 | }
89 |
90 | youTubePlayer.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
91 | @Override
92 | public void onPlaying() {
93 | if (listener != null && youTubePlayer != null && !PlayerStateList.PLAYING.equals(playerState)) {
94 | playerState = PlayerStateList.PLAYING;
95 | listener.onPlay(youTubePlayer.getCurrentTimeMillis());
96 | }
97 | }
98 |
99 | @Override
100 | public void onPaused() {
101 | handleOnPauseEvent();
102 | }
103 |
104 | @Override
105 | public void onStopped() {
106 | //since these are player stop events in case of any player error so pause event not stop.
107 | handleOnPauseEvent();
108 | }
109 |
110 | @Override
111 | public void onBuffering(boolean isBuffering) {
112 | if (listener != null && youTubePlayer != null) {
113 | listener.onBuffering((youTubePlayer.getCurrentTimeMillis()), isBuffering);
114 | }
115 | }
116 |
117 | @Override
118 | public void onSeekTo(int newPositionMillis) {
119 | //just to mimick the pause event before play on seek event.
120 | handleOnPauseEvent();
121 | }
122 | });
123 |
124 | youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
125 | @Override
126 | public void onLoading() {
127 | //intentionally left blank
128 | }
129 |
130 | @Override
131 | public void onLoaded(String s) {
132 | //intentionally left blank
133 | }
134 |
135 | @Override
136 | public void onAdStarted() {
137 | //intentionally left blank
138 | }
139 |
140 | @Override
141 | public void onVideoStarted() {
142 | //intentionally left blank
143 | }
144 |
145 | @Override
146 | public void onVideoEnded() {
147 | handleStopEvent();
148 | }
149 |
150 | @Override
151 | public void onError(YouTubePlayer.ErrorReason errorReason) {
152 | //intentionally left blank
153 | }
154 | });
155 |
156 | if (!restored) {
157 | //do any work here to cue video, play video, etc.
158 | Bundle arguments = getArguments();
159 | String videoId = arguments != null ? arguments.getString(ARG_VIDEO_ID) : null;
160 | if (!TextUtils.isEmpty(videoId)) {
161 | youTubePlayer.loadVideo(videoId);
162 | }
163 | }
164 | }
165 |
166 | private void handleOnPauseEvent() {
167 | if (listener != null && youTubePlayer != null && (PlayerStateList.PLAYING.equals(playerState)
168 | || PlayerStateList.BUFFERING.equals(playerState))) {
169 | playerState = PlayerStateList.PAUSED;
170 | listener.onPause((youTubePlayer.getCurrentTimeMillis()));
171 | }
172 | }
173 |
174 | private void handleStopEvent() {
175 | if (listener != null && youTubePlayer != null && (PlayerStateList.PLAYING.equals(playerState)
176 | || PlayerStateList.BUFFERING.equals(playerState) || PlayerStateList.PAUSED.equals(playerState))) {
177 | playerState = PlayerStateList.STOPPED;
178 | listener.onStop((youTubePlayer.getCurrentTimeMillis()), (youTubePlayer.getDurationMillis()));
179 | }
180 | }
181 |
182 | @Override
183 | public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
184 | youTubePlayer = null;
185 | if (listener != null) {
186 | listener.onInitializationFailure(result.name());
187 | }
188 | }
189 |
190 | @Override
191 | public void onStop() {
192 | super.onStop();
193 | handleStopEvent();
194 | release();
195 | }
196 |
197 | @Override
198 | public void onDestroyView() {
199 | super.onDestroyView();
200 | release();
201 | }
202 |
203 | @MainThread
204 | public void release() {
205 | if (youTubePlayer != null) {
206 | youTubePlayer.release();
207 | youTubePlayer = null;
208 | }
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/fragment/YouTubeWebViewFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.fragment;
20 |
21 | import android.os.Bundle;
22 | import androidx.annotation.NonNull;
23 | import androidx.annotation.Nullable;
24 | import androidx.fragment.app.Fragment;
25 | import android.text.TextUtils;
26 | import android.view.LayoutInflater;
27 | import android.view.View;
28 | import android.view.ViewGroup;
29 |
30 | import com.flipkart.youtubeview.R;
31 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
32 | import com.flipkart.youtubeview.webview.YouTubePlayerWebView;
33 |
34 | public final class YouTubeWebViewFragment extends Fragment implements YouTubeEventListener, YouTubeBaseFragment {
35 |
36 | private static final String WEB_VIEW_URL = "webViewUrl";
37 | private static final String VIDEO_ID = "videoId";
38 | private YouTubePlayerWebView youTubePlayerWebView = null;
39 |
40 | @Nullable
41 | private YouTubeEventListener youTubeEventListener;
42 |
43 | public static YouTubeWebViewFragment newInstance(@NonNull String webViewUrl, @NonNull String videoId) {
44 | YouTubeWebViewFragment fragment = new YouTubeWebViewFragment();
45 | Bundle bundle = new Bundle();
46 | bundle.putString(WEB_VIEW_URL, webViewUrl);
47 | bundle.putString(VIDEO_ID, videoId);
48 | fragment.setArguments(bundle);
49 | return fragment;
50 | }
51 |
52 | @Override
53 | public void setYouTubeEventListener(@Nullable YouTubeEventListener listener) {
54 | youTubeEventListener = listener;
55 | }
56 |
57 | @Override
58 | public void release() {
59 | if (youTubePlayerWebView != null) {
60 | youTubePlayerWebView.stopPlayer();
61 | }
62 | }
63 |
64 | public void setWebView(@NonNull YouTubePlayerWebView webView) {
65 | youTubePlayerWebView = webView;
66 | }
67 |
68 | @Nullable
69 | @Override
70 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
71 | Bundle arguments = getArguments();
72 | String webViewUrl = arguments != null ? arguments.getString(WEB_VIEW_URL) : null;
73 | if (TextUtils.isEmpty(webViewUrl)) {
74 | throw new IllegalStateException("webViewUrl cannot be null");
75 | }
76 | return bindYoutubePlayerWebView(inflater, container, webViewUrl);
77 | }
78 |
79 | private YouTubePlayerWebView bindYoutubePlayerWebView(LayoutInflater inflater, @Nullable ViewGroup container, @NonNull String webViewUrl) {
80 | if (youTubePlayerWebView == null) {
81 | youTubePlayerWebView = (YouTubePlayerWebView) inflater.inflate(R.layout.youtube_player_web_view, container, false);
82 | youTubePlayerWebView.initialize(webViewUrl);
83 | youTubePlayerWebView.setYouTubeListener(this);
84 | setWebViewProps();
85 | //on ready event will be fired by default
86 | } else {
87 | removeWebView();
88 | youTubePlayerWebView.initialize(webViewUrl);
89 | youTubePlayerWebView.setYouTubeListener(this);
90 | setWebViewProps();
91 | youTubePlayerWebView.onReadyPlayer();
92 | }
93 | return youTubePlayerWebView;
94 | }
95 |
96 | private void setWebViewProps() {
97 | youTubePlayerWebView.resetTime();
98 | }
99 |
100 | public YouTubePlayerWebView removeWebView() {
101 | youTubePlayerWebView.stopPlayer();
102 | return youTubePlayerWebView;
103 | }
104 |
105 | @Override
106 | public void onReady() {
107 | Bundle arguments = getArguments();
108 | String videoId = arguments != null ? arguments.getString(VIDEO_ID) : null;
109 | youTubePlayerWebView.loadVideo(videoId);
110 | if (youTubeEventListener != null) {
111 | youTubeEventListener.onReady();
112 | }
113 | }
114 |
115 | @Override
116 | public void onPlay(int currentTime) {
117 | if (youTubeEventListener != null) {
118 | youTubeEventListener.onPlay(currentTime);
119 | }
120 | }
121 |
122 | @Override
123 | public void onPause(int currentTime) {
124 | if (youTubeEventListener != null) {
125 | youTubeEventListener.onPause(currentTime);
126 | }
127 | }
128 |
129 | @Override
130 | public void onStop(int currentTime, int totalDuration) {
131 | if (youTubeEventListener != null) {
132 | youTubeEventListener.onStop(currentTime, totalDuration);
133 | }
134 | }
135 |
136 | @Override
137 | public void onBuffering(int currentTime, boolean isBuffering) {
138 | if (youTubeEventListener != null) {
139 | youTubeEventListener.onBuffering(currentTime, isBuffering);
140 | }
141 | }
142 |
143 | @Override
144 | public void onSeekTo(int currentTime, int newPositionMillis) {
145 | if (youTubeEventListener != null) {
146 | youTubeEventListener.onSeekTo(currentTime, newPositionMillis);
147 | }
148 | }
149 |
150 | @Override
151 | public void onInitializationFailure(String error) {
152 | if (youTubeEventListener != null) {
153 | youTubeEventListener.onInitializationFailure(error);
154 | }
155 | }
156 |
157 | @Override
158 | public void onNativeNotSupported() {
159 | if (youTubeEventListener != null) {
160 | youTubeEventListener.onNativeNotSupported();
161 | }
162 | }
163 |
164 | @Override
165 | public void onCued() {
166 | if (youTubeEventListener != null) {
167 | youTubeEventListener.onCued();
168 | }
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/listener/YouTubeEventListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.listener;
20 |
21 | import androidx.annotation.MainThread;
22 |
23 | public interface YouTubeEventListener {
24 |
25 | /**
26 | * fired when youtube player is ready
27 | */
28 | @MainThread
29 | void onReady();
30 |
31 | /**
32 | * when video is playing.
33 | *
34 | * @param currentTime currentTime of seek-bar
35 | */
36 | @MainThread
37 | void onPlay(int currentTime);
38 |
39 | /**
40 | * when video has been paused.
41 | *
42 | * @param currentTime paused time
43 | */
44 | @MainThread
45 | void onPause(int currentTime);
46 |
47 | /**
48 | * when video has been stopped
49 | *
50 | * @param currentTime stop time
51 | * @param totalDuration total duration of video
52 | */
53 | @MainThread
54 | void onStop(int currentTime, int totalDuration);
55 |
56 | /**
57 | * when video is buffering
58 | *
59 | * @param currentTime current buffering time
60 | * @param isBuffering is video being buffered
61 | */
62 | @MainThread
63 | void onBuffering(int currentTime, boolean isBuffering);
64 |
65 | /**
66 | * when seek-bar is moved
67 | *
68 | * @param currentTime time from where seek-bar has been moved
69 | * @param newPositionMillis new position moved
70 | */
71 | @MainThread
72 | void onSeekTo(int currentTime, int newPositionMillis);
73 |
74 | /**
75 | * when youtube player fails to initialize
76 | *
77 | * @param error message
78 | */
79 | @MainThread
80 | void onInitializationFailure(String error);
81 |
82 | /**
83 | * when native player is not supported
84 | */
85 | @MainThread
86 | void onNativeNotSupported();
87 |
88 | /**
89 | * when video is cued
90 | */
91 | @MainThread
92 | void onCued();
93 | }
94 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/models/ImageLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.models;
20 |
21 | import androidx.annotation.NonNull;
22 | import android.widget.ImageView;
23 |
24 | public interface ImageLoader {
25 | /**
26 | * Callback to load image (thumbnail view)
27 | *
28 | * @param imageView imageview
29 | * @param url url of image
30 | * @param height height
31 | * @param width width
32 | */
33 | void loadImage(@NonNull ImageView imageView, @NonNull String url, int height, int width);
34 | }
35 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/models/PlayerStateList.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.models;
20 |
21 | import androidx.annotation.StringDef;
22 |
23 | import java.lang.annotation.Retention;
24 | import java.lang.annotation.RetentionPolicy;
25 |
26 | @SuppressWarnings("WeakerAccess")
27 | public class PlayerStateList {
28 | public static final String NOT_STARTED = "NOT_STARTED";
29 | public static final String ENDED = "ENDED";
30 | public static final String PLAYING = "PLAYING";
31 | public static final String PAUSED = "PAUSED";
32 | public static final String BUFFERING = "BUFFERING";
33 | public static final String CUED = "CUED";
34 | public static final String NONE = "NONE";
35 | public static final String STOPPED = "STOPPED";
36 |
37 | @StringDef({NOT_STARTED, ENDED, PLAYING, PAUSED, BUFFERING, CUED, NONE, STOPPED})
38 | @Retention(RetentionPolicy.SOURCE)
39 | public @interface PlayerState {
40 | }
41 | }
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/models/YouTubePlayerType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.models;
20 |
21 | import androidx.annotation.IntDef;
22 |
23 | import java.lang.annotation.Retention;
24 | import java.lang.annotation.RetentionPolicy;
25 |
26 | @IntDef({YouTubePlayerType.INVALID_VIEW, YouTubePlayerType.AUTO, YouTubePlayerType.STRICT_NATIVE, YouTubePlayerType.WEB_VIEW})
27 | @Retention(RetentionPolicy.SOURCE)
28 | public @interface YouTubePlayerType {
29 | /**
30 | * Invalid view
31 | */
32 | int INVALID_VIEW = 0;
33 |
34 | /**
35 | * Auto. If youtube service is available, it will render native player
36 | * else will fallback to WebView if web-url provided
37 | */
38 | int AUTO = 1;
39 |
40 | /**
41 | * render only native player
42 | */
43 | int STRICT_NATIVE = 2;
44 |
45 | /**
46 | * render only WebView player
47 | */
48 | int WEB_VIEW = 3;
49 | }
50 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/util/$Precondition$Check.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.util;
20 |
21 | public final class $Precondition$Check {
22 | /**
23 | * Ensures that an expression checking an argument is true.
24 | *
25 | * @param expression the expression to check
26 | * @param errorMessage the exception message to use if the check fails; will
27 | * be converted to a string using {@link String#valueOf(Object)}
28 | * @throws IllegalArgumentException if {@code expression} is false
29 | */
30 | public static void checkArgument(boolean expression, final Object errorMessage) {
31 | if (!expression) {
32 | throw new IllegalArgumentException(String.valueOf(errorMessage));
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/util/ServiceUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.util;
20 |
21 | import android.content.Context;
22 |
23 | import com.google.android.youtube.player.YouTubeApiServiceUtil;
24 | import com.google.android.youtube.player.YouTubeInitializationResult;
25 | import com.google.android.youtube.player.YouTubeIntents;
26 |
27 | public final class ServiceUtil {
28 |
29 | /**
30 | * Check if youtube service is available
31 | *
32 | * @param context {@link Context}
33 | * @return true if present, else false
34 | */
35 | public static boolean isYouTubeServiceAvailable(Context context) {
36 | return YouTubeIntents.isYouTubeInstalled(context) ||
37 | YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(context) == YouTubeInitializationResult.SUCCESS;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/java/com/flipkart/youtubeview/webview/YouTubePlayerWebView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Apache License
3 | * Version 2.0, January 2004
4 | * http://www.apache.org/licenses/LICENSE-2.0
5 | *
6 | * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 | *
8 | * Copyright (c) 2018 Flipkart Internet Pvt. Ltd.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
11 | * this file except in compliance with the License. You may obtain a copy of the
12 | * License at http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software distributed
15 | * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16 | * CONDITIONS OF ANY KIND, either express or implied. See the License for the
17 | * specific language governing permissions and limitations under the License.
18 | */
19 | package com.flipkart.youtubeview.webview;
20 |
21 | import android.annotation.SuppressLint;
22 | import android.content.Context;
23 | import android.net.Uri;
24 | import android.os.Build;
25 | import androidx.annotation.NonNull;
26 | import androidx.annotation.Nullable;
27 | import androidx.annotation.RequiresApi;
28 | import android.text.TextUtils;
29 | import android.util.AttributeSet;
30 | import android.util.Log;
31 | import android.view.View;
32 | import android.webkit.WebResourceRequest;
33 | import android.webkit.WebSettings;
34 | import android.webkit.WebView;
35 | import android.webkit.WebViewClient;
36 |
37 | import com.flipkart.youtubeview.BuildConfig;
38 | import com.flipkart.youtubeview.listener.YouTubeEventListener;
39 | import com.flipkart.youtubeview.models.PlayerStateList;
40 | import com.flipkart.youtubeview.util.$Precondition$Check;
41 |
42 | public class YouTubePlayerWebView extends WebView {
43 |
44 | private static final String TAG = "YoutubePlayerWebView";
45 | private static final String SCHEME = "ytplayer";
46 | private static final String DATA_QUERY_PARAM = "data";
47 | private static final String CURRENT_TIME_PARAM = "currentTime";
48 | private static final String EVENT_CALLBACK = "callback";
49 | private static final int MULTIPLIER = 1000;
50 | private static final double ASPECT_RATIO = 0.5625; //aspect ratio of player 9:16(height/width)
51 |
52 | @Nullable
53 | private YouTubeEventListener youTubeListener;
54 |
55 | private String duration = null;
56 | private String currentTime = null;
57 | private String previousState = PlayerStateList.NONE;
58 | private boolean isPlayerReady = false;
59 |
60 | public YouTubePlayerWebView(Context context) {
61 | super(context);
62 | }
63 |
64 | public YouTubePlayerWebView(Context context, AttributeSet attrs) {
65 | super(context, attrs);
66 | }
67 |
68 | @Override
69 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
70 | super.onMeasure(widthMeasureSpec, heightMeasureSpec);
71 |
72 | int newWidth;
73 | int newHeight;
74 | newWidth = getMeasuredWidth();
75 | newHeight = (int) (newWidth * ASPECT_RATIO);
76 | setMeasuredDimension(newWidth, newHeight);
77 | }
78 |
79 | public void initialize(@NonNull String webViewUrl) {
80 | $Precondition$Check.checkArgument(!TextUtils.isEmpty(webViewUrl), "WebView url cannot be empty");
81 | if (!isPlayerReady) {
82 | initWebView(webViewUrl);
83 | }
84 | }
85 |
86 | public void setYouTubeListener(@Nullable YouTubeEventListener listener) {
87 | this.youTubeListener = listener;
88 | }
89 |
90 | public void resetTime() {
91 | duration = null;
92 | currentTime = null;
93 | previousState = PlayerStateList.NONE;
94 | }
95 |
96 | /**
97 | * Initialises YoutubeWebView with given videoId and youtubeListener
98 | */
99 | @SuppressLint("SetJavaScriptEnabled")
100 | private void initWebView(String webViewUrl) {
101 | WebSettings set = this.getSettings();
102 | set.setJavaScriptEnabled(true);
103 | set.setUseWideViewPort(true);
104 | set.setLoadWithOverviewMode(true);
105 | set.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
106 | set.setCacheMode(WebSettings.LOAD_DEFAULT);
107 | set.setPluginState(WebSettings.PluginState.ON_DEMAND);
108 | set.setAllowContentAccess(true);
109 | set.setAllowFileAccess(false);
110 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
111 | set.setMediaPlaybackRequiresUserGesture(false);
112 | }
113 | this.setLayerType(View.LAYER_TYPE_NONE, null);
114 | this.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
115 | this.loadUrl(webViewUrl);
116 |
117 | if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
118 | setWebContentsDebuggingEnabled(true);
119 | }
120 |
121 | this.setWebViewClient(initWebViewClient());
122 | }
123 |
124 | @NonNull
125 | private WebViewClient initWebViewClient() {
126 | return new WebViewClient() {
127 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
128 | @Override
129 | public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
130 | return shouldOverrideUrlLoading(request.getUrl());
131 | }
132 |
133 | @Override
134 | public boolean shouldOverrideUrlLoading(WebView view, String url) {
135 | if (!TextUtils.isEmpty(url)) {
136 | Uri uri = Uri.parse(url);
137 | return shouldOverrideUrlLoading(uri);
138 | } else {
139 | return false;
140 | }
141 | }
142 |
143 | private boolean shouldOverrideUrlLoading(@NonNull Uri url) {
144 | if (SCHEME.equals(url.getScheme())) {
145 | String methodName = url.getHost();
146 | String data = url.getQueryParameter(DATA_QUERY_PARAM);
147 | String paramCurrentTime = url.getQueryParameter(CURRENT_TIME_PARAM);
148 | String eventCallBack = url.getQueryParameter(EVENT_CALLBACK);
149 |
150 | if (!TextUtils.isEmpty(eventCallBack)) {
151 | sendAck(eventCallBack, methodName);
152 | }
153 | if (!TextUtils.isEmpty(paramCurrentTime)) {
154 | currentTime(paramCurrentTime);
155 | }
156 | if (!TextUtils.isEmpty(methodName)) {
157 | invokeNativeMethod(methodName, data);
158 | }
159 | }
160 | return true; // return true in all case as webView shouldn't allow any other url to open.
161 | }
162 | };
163 | }
164 |
165 | @Override
166 | public void onScreenStateChanged(int screenState) {
167 | if (screenState == SCREEN_STATE_OFF) {
168 | stopPlayer();
169 | }
170 | }
171 |
172 | private void invokeNativeMethod(@NonNull String methodName, String args) {
173 | switch (methodName) {
174 | case "onReady":
175 | onReady(args);
176 | break;
177 | case "onStateChange":
178 | onStateChange(args);
179 | break;
180 | case "onPlaybackQualityChange":
181 | onPlaybackQualityChange(args);
182 | break;
183 | case "onPlaybackRateChange":
184 | onPlaybackRateChange(args);
185 | break;
186 | case "onError":
187 | onError(args);
188 | break;
189 | case "onApiChange":
190 | onApiChange(args);
191 | break;
192 | case "currentTime":
193 | currentTime(args);
194 | break;
195 | case "duration":
196 | duration(args);
197 | break;
198 | case "logs":
199 | logs(args);
200 | break;
201 | case "onYouTubeIframeAPIFailedToLoad":
202 | onYouTubeIframeAPIFailedToLoad(args);
203 | break;
204 | case "onYouTubeIframeAPIReady":
205 | onYouTubeIframeAPIReady(args);
206 | break;
207 | default:
208 | break;
209 | }
210 | }
211 |
212 | /**
213 | * APP TO WEB API's
214 | */
215 | @SuppressWarnings("unused")
216 | public void seekToMillis(double mil) {
217 | if (BuildConfig.DEBUG) {
218 | Log.d(TAG, "seekToMillis : ");
219 | }
220 | this.loadUrl("javascript:onSeekTo(" + mil + ")");
221 | }
222 |
223 | @SuppressWarnings("unused")
224 | public void pause() {
225 | if (BuildConfig.DEBUG) {
226 | Log.d(TAG, "pause");
227 | }
228 | this.loadUrl("javascript:onVideoPause()");
229 | }
230 |
231 | public void stop() {
232 | if (BuildConfig.DEBUG) {
233 | Log.d(TAG, "stop");
234 | }
235 | if (youTubeListener != null) {
236 | youTubeListener.onStop(getTimeInMilliSec(currentTime), getTimeInMilliSec(duration));
237 | }
238 | this.loadUrl("javascript:onVideoStop()");
239 | }
240 |
241 | public void setDuration() {
242 | if (BuildConfig.DEBUG) {
243 | Log.d(TAG, "setDuration");
244 | }
245 | this.loadUrl("javascript:sendDuration()");
246 | }
247 |
248 | @SuppressWarnings("unused")
249 | public void play() {
250 | if (BuildConfig.DEBUG) {
251 | Log.d(TAG, "play");
252 | }
253 | this.loadUrl("javascript:onVideoPlay()");
254 | }
255 |
256 | public void loadVideo(String videoId) {
257 | if (BuildConfig.DEBUG) {
258 | Log.d(TAG, "loadVideo : " + videoId);
259 | }
260 | this.loadUrl("javascript:loadVideo('" + videoId + "')");
261 | }
262 |
263 | @SuppressWarnings("unused")
264 | public void cueVideo(String videoId) {
265 | if (BuildConfig.DEBUG) {
266 | Log.d(TAG, "cueVideo : " + videoId);
267 | }
268 | this.loadUrl("javascript:cueVideo('" + videoId + "')");
269 | }
270 |
271 | private void sendAck(String callBack, String methodName) {
272 | if (BuildConfig.DEBUG) {
273 | Log.d(TAG, "sendAck for :" + methodName);
274 | }
275 | this.loadUrl("javascript:" + callBack);
276 | }
277 |
278 | //It will make player ready for next video being played
279 | public void onReadyPlayer() {
280 | if (youTubeListener != null && isPlayerReady) {
281 | youTubeListener.onReady();
282 | }
283 | }
284 |
285 | /**
286 | * WEB TO APP
287 | */
288 | private void onReady(@NonNull String arg) {
289 | if (BuildConfig.DEBUG) {
290 | Log.d(TAG, "onReady(" + arg + ")");
291 | }
292 |
293 | isPlayerReady = true;
294 | if (youTubeListener != null) {
295 | youTubeListener.onReady();
296 | }
297 | }
298 |
299 | private void onStateChange(String arg) {
300 | if (BuildConfig.DEBUG) {
301 | Log.d(TAG, "onStateChange(" + arg + ")");
302 | }
303 | previousState = arg;
304 | if (youTubeListener != null) {
305 | //noinspection StatementWithEmptyBody
306 | if (PlayerStateList.NOT_STARTED.equalsIgnoreCase(arg)) {
307 | //handle when needed.
308 | } else if (PlayerStateList.ENDED.equalsIgnoreCase(arg)) {
309 | youTubeListener.onStop(getTimeInMilliSec(currentTime), getTimeInMilliSec(duration));
310 | } else if (PlayerStateList.PLAYING.equalsIgnoreCase(arg)) {
311 | if (TextUtils.isEmpty(duration)) {
312 | setDuration();
313 | }
314 | youTubeListener.onPlay(getTimeInMilliSec(currentTime));
315 | } else if (PlayerStateList.PAUSED.equalsIgnoreCase(arg)) {
316 | youTubeListener.onPause(getTimeInMilliSec(currentTime));
317 | } else if (PlayerStateList.BUFFERING.equalsIgnoreCase(arg)) {
318 | youTubeListener.onBuffering(getTimeInMilliSec(currentTime), true);
319 | } else if (PlayerStateList.CUED.equalsIgnoreCase(arg)) {
320 | youTubeListener.onCued();
321 | }
322 | }
323 | }
324 |
325 | private void onPlaybackQualityChange(String arg) {
326 | if (BuildConfig.DEBUG) {
327 | Log.d(TAG, "onPlaybackQualityChange(" + arg + ")");
328 | }
329 | }
330 |
331 | private void onPlaybackRateChange(String arg) {
332 | if (BuildConfig.DEBUG) {
333 | Log.d(TAG, "onPlaybackRateChange(" + arg + ")");
334 | }
335 | }
336 |
337 | private void onError(String arg) {
338 | if (BuildConfig.DEBUG) {
339 | Log.e(TAG, "onError(" + arg + ")");
340 | }
341 | if (youTubeListener != null) {
342 | youTubeListener.onInitializationFailure(arg);
343 | }
344 | }
345 |
346 | private void onApiChange(String arg) {
347 | if (BuildConfig.DEBUG) {
348 | Log.d(TAG, "onApiChange(" + arg + ")");
349 | }
350 | }
351 |
352 | private void duration(String seconds) {
353 | if (!TextUtils.isEmpty(seconds) && !"UNDEFINED".equalsIgnoreCase(seconds)) {
354 | duration = seconds;
355 | }
356 | }
357 |
358 | private void currentTime(String seconds) {
359 | if (!TextUtils.isEmpty(seconds)) {
360 | currentTime = seconds;
361 | }
362 | }
363 |
364 | private void logs(String arg) {
365 | if (BuildConfig.DEBUG) {
366 | Log.d(TAG, "logs(" + arg + ")");
367 | }
368 | }
369 |
370 | private void onYouTubeIframeAPIFailedToLoad(String args) {
371 | if (youTubeListener != null) {
372 | youTubeListener.onInitializationFailure(args);
373 | }
374 | }
375 |
376 | @SuppressWarnings("unused")
377 | private void onYouTubeIframeAPIReady(String args) {
378 | //intentionally empty
379 | }
380 |
381 | private int getTimeInMilliSec(String seconds) {
382 | double time = 0.0;
383 | if (!TextUtils.isEmpty(seconds)) {
384 | try {
385 | time = Double.parseDouble(seconds) * MULTIPLIER;
386 | } catch (NumberFormatException ignored) {
387 | Log.e(TAG, ignored.getMessage());
388 | }
389 | }
390 | return (int) time;
391 | }
392 |
393 | public void stopPlayer() {
394 | if (isPlayerReady
395 | && (PlayerStateList.PLAYING.equals(previousState)
396 | || PlayerStateList.BUFFERING.equals(previousState)
397 | || PlayerStateList.PAUSED.equals(previousState)
398 | || PlayerStateList.CUED.equals(previousState))) {
399 | stop();
400 | }
401 | }
402 | }
403 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/drawable-hdpi/play_btn_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/inline-youtube-view/src/main/res/drawable-hdpi/play_btn_thumbnail.png
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/drawable-xhdpi/play_btn_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/inline-youtube-view/src/main/res/drawable-xhdpi/play_btn_thumbnail.png
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/drawable-xxhdpi/play_btn_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/inline-youtube-view/src/main/res/drawable-xxhdpi/play_btn_thumbnail.png
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/layout/recycler_progressbar.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/layout/video_container.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
19 |
20 |
26 |
27 |
32 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/layout/youtube_player_view.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/layout/youtube_player_web_view.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/values/color.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | #2196F3
5 | #000000
6 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 35dp
4 | 48dp
5 |
6 |
--------------------------------------------------------------------------------
/inline-youtube-view/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | inline-youtube-view
3 |
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':inline-youtube-view'
2 |
--------------------------------------------------------------------------------
/youtube-activity-android.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/youtube-activity-android.gif
--------------------------------------------------------------------------------
/youtube-fragment-android.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/flipkart-incubator/android-inline-youtube-view/2121245b9e6659136275ffa79115a3551c1826da/youtube-fragment-android.gif
--------------------------------------------------------------------------------
/youtube_iframe_player.html:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 |
34 |
36 |
38 |
39 |
40 |
41 |
42 |
45 |
46 |
47 |
237 |
238 |
239 |
--------------------------------------------------------------------------------