├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable
│ │ │ ├── movie.png
│ │ │ ├── cast_video.png
│ │ │ └── default_background.xml
│ │ ├── values
│ │ │ ├── styles.xml
│ │ │ ├── colors.xml
│ │ │ └── strings.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── java
│ │ └── com
│ │ │ └── google
│ │ │ └── sample
│ │ │ └── cast
│ │ │ └── atvreceiver
│ │ │ ├── ui
│ │ │ ├── MainActivity.java
│ │ │ ├── PlaybackActivity.java
│ │ │ ├── MainFragment.java
│ │ │ └── PlaybackVideoFragment.java
│ │ │ ├── CastReceiverOptionsProvider.java
│ │ │ ├── AppLifecycleObserver.java
│ │ │ ├── data
│ │ │ ├── MovieListLoader.java
│ │ │ ├── Movie.java
│ │ │ └── MovieList.java
│ │ │ ├── CastDemoApplication.java
│ │ │ ├── player
│ │ │ └── VideoPlayerGlue.java
│ │ │ └── presenter
│ │ │ └── CardPresenter.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── CONTRIBUTING.md
├── README.md
├── gradlew.bat
├── gradlew
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | rootProject.name='CastATVReceiver'
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shivasiddharth/CastAndroidTvReceiver/master/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/movie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shivasiddharth/CastAndroidTvReceiver/master/app/src/main/res/drawable/movie.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/cast_video.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shivasiddharth/CastAndroidTvReceiver/master/app/src/main/res/drawable/cast_video.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | .idea
11 | build
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Jun 16 11:15:26 PDT 2020
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-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/default_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 | #000000
3 | #DDDDDD
4 | #0096a6
5 | #ffaa3f
6 | #ffaa3f
7 | #3d3d3d
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Cast Videos
3 |
4 | Related Videos
5 | Watch video
6 | FREE
7 | Movie
8 |
9 | https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json
10 |
11 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/ui/MainActivity.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.ui;
17 |
18 | import android.app.Activity;
19 | import android.os.Bundle;
20 |
21 | import com.google.sample.cast.atvreceiver.R;
22 | /**
23 | * Main Activity class that loads {@link MainFragment}.
24 | */
25 | public class MainActivity extends Activity {
26 |
27 | public static final String MOVIE = "Movie";
28 |
29 | @Override
30 | public void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/CastReceiverOptionsProvider.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver;
17 |
18 | import android.content.Context;
19 | import com.google.android.gms.cast.tv.CastReceiverOptions;
20 | import com.google.android.gms.cast.tv.ReceiverOptionsProvider;
21 |
22 | public class CastReceiverOptionsProvider implements ReceiverOptionsProvider {
23 | @Override
24 | public CastReceiverOptions getOptions(Context context) {
25 | return new CastReceiverOptions.Builder(context)
26 | .setVersionCode(1)
27 | .setStatusText("Cast ATV Sample Receiver")
28 | .build();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | defaultConfig {
6 | applicationId "com.google.sample.cast.atvreceiver"
7 | minSdkVersion 21
8 | targetSdkVersion 28
9 | versionCode 1
10 | versionName "1.0"
11 | }
12 | buildTypes {
13 | release {
14 | minifyEnabled false
15 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
16 | }
17 | }
18 | compileOptions {
19 | targetCompatibility JavaVersion.VERSION_1_8
20 | sourceCompatibility JavaVersion.VERSION_1_8
21 | }
22 | }
23 |
24 | dependencies {
25 | implementation 'androidx.leanback:leanback:1.0.0'
26 | implementation 'androidx.appcompat:appcompat:1.1.0'
27 | implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
28 | implementation 'androidx.lifecycle:lifecycle-common-java8:2.1.0'
29 | implementation 'com.github.bumptech.glide:glide:4.9.0'
30 |
31 | // Exoplayer
32 | implementation 'com.google.android.exoplayer:exoplayer:2.10.0'
33 | implementation 'com.google.android.exoplayer:extension-leanback:2.10.0'
34 | implementation 'com.google.android.exoplayer:extension-mediasession:2.10.0'
35 |
36 | // Cast Connect libraries
37 | implementation 'com.google.android.gms:play-services-cast-tv:17.0.0'
38 | implementation 'com.google.android.gms:play-services-cast:19.0.0'
39 | }
40 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your sample apps and patches! Before we can take them, we
6 | have to jump a couple of legal hurdles.
7 |
8 | Please fill out either the individual or corporate Contributor License Agreement
9 | (CLA).
10 |
11 | * If you are an individual writing original source code and you're sure you
12 | own the intellectual property, then you'll need to sign an [individual CLA]
13 | (https://cla.developers.google.com/about/google-individual).
14 | * If you work for a company that wants to allow you to contribute your work,
15 | then you'll need to sign a [corporate CLA]
16 | (https://cla.developers.google.com/about/google-corporate).
17 |
18 | Follow either of the two links above to access the appropriate CLA and
19 | instructions for how to sign and return it. Once we receive it, we'll be able to
20 | accept your pull requests.
21 |
22 | ## Contributing a Patch
23 |
24 | 1. Sign a Contributor License Agreement, if you have not yet done so (see
25 | details above).
26 | 1. Create your change to the repo in question.
27 | * Fork the desired repo, develop and test your code changes.
28 | * Ensure that your code is clear and comprehensible.
29 | * Ensure that your code has an appropriate set of unit tests which all pass.
30 | 1. Submit a pull request.
31 | 1. The repo owner will review your request. If it is approved, the change will
32 | be merged. If it needs additional work, the repo owner will respond with
33 | useful comments.
34 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/AppLifecycleObserver.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver;
17 |
18 | import androidx.annotation.NonNull;
19 | import androidx.lifecycle.DefaultLifecycleObserver;
20 | import androidx.lifecycle.LifecycleOwner;
21 | import com.google.android.gms.cast.tv.CastReceiverContext;
22 |
23 | public class AppLifecycleObserver implements DefaultLifecycleObserver {
24 | @Override
25 | public void onResume(LifecycleOwner owner) {
26 | }
27 |
28 | @Override
29 | public void onPause(LifecycleOwner owner) {
30 | }
31 |
32 | @Override
33 | public void onDestroy(LifecycleOwner owner) {
34 | }
35 |
36 | @Override
37 | public void onCreate(@NonNull LifecycleOwner owner) {
38 | }
39 |
40 | @Override
41 | public void onStart(@NonNull LifecycleOwner owner) {
42 | CastReceiverContext.getInstance().start();
43 | }
44 |
45 | @Override
46 | public void onStop(LifecycleOwner owner) {
47 | CastReceiverContext.getInstance().stop();
48 | }
49 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/data/MovieListLoader.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.data;
17 |
18 | import android.content.AsyncTaskLoader;
19 | import android.content.Context;
20 | import android.util.Log;
21 |
22 | import java.util.List;
23 |
24 | public class MovieListLoader extends AsyncTaskLoader> {
25 |
26 | private static final String TAG = "MovieListLoader";
27 | private final String mUrl;
28 |
29 | public MovieListLoader(Context context, String url) {
30 | super(context);
31 | this.mUrl = url;
32 | }
33 |
34 | @Override
35 | public List loadInBackground() {
36 | try {
37 | return MovieList.setupMovies(mUrl);
38 | } catch (Exception e) {
39 | Log.e(TAG, "Failed to fetch media data", e);
40 | return null;
41 | }
42 | }
43 |
44 | @Override
45 | protected void onStartLoading() {
46 | super.onStartLoading();
47 | forceLoad();
48 | }
49 |
50 | @Override
51 | protected void onStopLoading() {
52 | // Attempt to cancel the current load task if possible.
53 | cancelLoad();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Cast Android TV Sample App
2 |
3 | This sample shows how to develop a Cast Connect-enabled Android TV app.
4 |
5 | [List of reference apps and tutorials](https://developers.google.com/cast/docs/downloads)
6 |
7 | ## Setup Instructions
8 | 1. Use an existing Web Receiver or [create a new Web Receiver](https://developers.google.com/cast/docs/caf_receiver).
9 | 1. Follow the steps for [setting up the Cast Developer Console](https://developers.google.com/cast/docs/android_tv_receiver/core_features#cast_developer_console_setup).
10 | 1. Follow the steps for [setting up your sender app for Cast Connect support](https://developers.google.com/cast/docs/android_tv_receiver/core_features#sender_app_setup).
11 | 1. You should now be able to launch your Android TV Receiver using a sender.
12 | 1. If you are unable to launch the Android TV Receiver, follow the [Troubleshooting Guide](https://developers.google.com/cast/docs/android_tv_receiver/core_features#troubleshooting).
13 |
14 | ## Documentation
15 | * [Google Cast Android TV Overview](https://developers.google.com/cast/docs/android_tv_receiver)
16 | * [Developer Guides](https://developers.google.com/cast/docs/developers)
17 |
18 | ## References
19 | * [Android TV Receiver Reference](https://developers.google.com/cast/docs/reference/atv_receiver/packages)
20 |
21 | ## How to report bugs
22 | * [Google Cast SDK Support](https://developers.google.com/cast/support)
23 | * For sample app issues, open an issue on this GitHub repo.
24 |
25 | ## Contributions
26 | Please read and follow the steps in the [CONTRIBUTING.md](CONTRIBUTING.md).
27 |
28 | ## License
29 | See [LICENSE](LICENSE).
30 |
31 | ## Terms
32 | Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/) and the [Google Cast SDK Additional Developer Terms of Service](https://developers.google.com/cast/docs/terms/).
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/ui/PlaybackActivity.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.ui;
17 |
18 | import android.content.Intent;
19 | import android.os.Bundle;
20 |
21 | import androidx.fragment.app.FragmentActivity;
22 | import com.google.android.gms.cast.tv.CastReceiverContext;
23 | import com.google.android.gms.cast.tv.media.MediaManager;
24 | /**
25 | * Loads {@link PlaybackVideoFragment}.
26 | */
27 | public class PlaybackActivity extends FragmentActivity {
28 |
29 | private PlaybackVideoFragment playbackVideoFragment;
30 |
31 | @Override
32 | public void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 |
35 | playbackVideoFragment = new PlaybackVideoFragment();
36 | if (savedInstanceState == null) {
37 | getSupportFragmentManager()
38 | .beginTransaction()
39 | .replace(android.R.id.content, playbackVideoFragment)
40 | .commit();
41 | }
42 | }
43 |
44 | @Override
45 | protected void onNewIntent(Intent intent) {
46 | super.onNewIntent(intent);
47 |
48 | MediaManager mediaManager = CastReceiverContext.getInstance().getMediaManager();
49 | if (mediaManager.onNewIntent(intent)) {
50 | // If the SDK recognizes the intent, you should early return.
51 | return;
52 | }
53 |
54 | // If the SDK doesn’t recognize the intent, you can handle the intent with
55 | // your own logic.
56 | playbackVideoFragment.processIntent(intent);
57 | }
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/CastDemoApplication.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver;
17 |
18 | import android.app.Application;
19 |
20 | import android.widget.Toast;
21 |
22 | import androidx.lifecycle.ProcessLifecycleOwner;
23 |
24 | import com.google.android.gms.cast.tv.CastReceiverContext;
25 | import com.google.android.gms.cast.tv.SenderDisconnectedEventInfo;
26 | import com.google.android.gms.cast.tv.SenderInfo;
27 |
28 | public class CastDemoApplication extends Application {
29 |
30 | @Override
31 | public void onCreate() {
32 | super.onCreate();
33 | CastReceiverContext.initInstance(this);
34 | CastReceiverContext.getInstance().registerEventCallback(new EventCallback());
35 | ProcessLifecycleOwner.get().getLifecycle().addObserver(new AppLifecycleObserver());
36 | }
37 |
38 | private class EventCallback extends CastReceiverContext.EventCallback {
39 | @Override
40 | public void onSenderConnected(SenderInfo senderInfo) {
41 | Toast.makeText(
42 | CastDemoApplication.this,
43 | "Sender connected " + senderInfo.getSenderId(),
44 | Toast.LENGTH_LONG)
45 | .show();
46 | }
47 |
48 | @Override
49 | public void onSenderDisconnected(SenderDisconnectedEventInfo eventInfo) {
50 | Toast.makeText(
51 | CastDemoApplication.this,
52 | "Sender disconnected " + eventInfo.getSenderInfo().getSenderId(),
53 | Toast.LENGTH_LONG)
54 | .show();
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
11 |
14 |
15 |
23 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
43 |
44 |
45 |
46 |
47 |
48 |
56 |
57 |
60 |
61 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/data/Movie.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.data;
17 |
18 | import java.io.Serializable;
19 |
20 |
21 | /**
22 | * Movie class represents video entity with title, description, image thumbs and video url.
23 | */
24 | public class Movie implements Serializable {
25 | static final long serialVersionUID = 727566175075960653L;
26 | private int id;
27 | private String title;
28 | private String description;
29 | private String bgImageUrl;
30 | private String cardImageUrl;
31 | private String videoUrl;
32 | private String studio;
33 |
34 | public Movie() {
35 | }
36 |
37 | public int getId() {
38 | return id;
39 | }
40 |
41 | public void setId(int id) {
42 | this.id = id;
43 | }
44 |
45 | public String getTitle() {
46 | return title;
47 | }
48 |
49 | public void setTitle(String title) {
50 | this.title = title;
51 | }
52 |
53 | public String getDescription() {
54 | return description;
55 | }
56 |
57 | public void setDescription(String description) {
58 | this.description = description;
59 | }
60 |
61 | public String getStudio() {
62 | return studio;
63 | }
64 |
65 | public void setStudio(String studio) {
66 | this.studio = studio;
67 | }
68 |
69 | public String getVideoUrl() {
70 | return videoUrl;
71 | }
72 |
73 | public void setVideoUrl(String videoUrl) {
74 | this.videoUrl = videoUrl;
75 | }
76 |
77 | public String getBackgroundImageUrl() {
78 | return bgImageUrl;
79 | }
80 |
81 | public void setBackgroundImageUrl(String bgImageUrl) {
82 | this.bgImageUrl = bgImageUrl;
83 | }
84 |
85 | public String getCardImageUrl() {
86 | return cardImageUrl;
87 | }
88 |
89 | public void setCardImageUrl(String cardImageUrl) {
90 | this.cardImageUrl = cardImageUrl;
91 | }
92 |
93 | @Override
94 | public String toString() {
95 | return "Movie{" +
96 | "id=" + id +
97 | ", title='" + title + '\'' +
98 | ", videoUrl='" + videoUrl + '\'' +
99 | ", backgroundImageUrl='" + bgImageUrl + '\'' +
100 | ", cardImageUrl='" + cardImageUrl + '\'' +
101 | '}';
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/player/VideoPlayerGlue.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.player;
17 |
18 | import android.content.Context;
19 | import androidx.leanback.media.PlaybackTransportControlGlue;
20 | import androidx.leanback.widget.Action;
21 | import androidx.leanback.widget.ArrayObjectAdapter;
22 | import androidx.leanback.widget.PlaybackControlsRow;
23 | import com.google.android.exoplayer2.ext.leanback.LeanbackPlayerAdapter;
24 | import java.util.concurrent.TimeUnit;
25 |
26 | public class VideoPlayerGlue extends PlaybackTransportControlGlue {
27 |
28 | private static final long TEN_SECONDS = TimeUnit.SECONDS.toMillis(10);
29 |
30 | /** Listens for when skip to next and previous actions have been dispatched. */
31 | public interface OnActionClickedListener {
32 |
33 | /** Skip to the previous item in the queue. */
34 | void onPrevious();
35 |
36 | /** Skip to the next item in the queue. */
37 | void onNext();
38 | }
39 |
40 | private final OnActionClickedListener mActionListener;
41 |
42 | private PlaybackControlsRow.SkipPreviousAction mSkipPreviousAction;
43 | private PlaybackControlsRow.SkipNextAction mSkipNextAction;
44 | private PlaybackControlsRow.FastForwardAction mFastForwardAction;
45 | private PlaybackControlsRow.RewindAction mRewindAction;
46 |
47 | public VideoPlayerGlue(
48 | Context context,
49 | LeanbackPlayerAdapter playerAdapter,
50 | OnActionClickedListener actionListener) {
51 | super(context, playerAdapter);
52 |
53 | mActionListener = actionListener;
54 |
55 | mSkipPreviousAction = new PlaybackControlsRow.SkipPreviousAction(context);
56 | mSkipNextAction = new PlaybackControlsRow.SkipNextAction(context);
57 | mFastForwardAction = new PlaybackControlsRow.FastForwardAction(context);
58 | mRewindAction = new PlaybackControlsRow.RewindAction(context);
59 | }
60 |
61 | @Override
62 | protected void onCreatePrimaryActions(ArrayObjectAdapter primaryActionsAdapter) {
63 | super.onCreatePrimaryActions(primaryActionsAdapter);
64 | primaryActionsAdapter.add(mSkipPreviousAction);
65 | primaryActionsAdapter.add(mRewindAction);
66 | primaryActionsAdapter.add(mFastForwardAction);
67 | primaryActionsAdapter.add(mSkipNextAction);
68 | }
69 |
70 | @Override
71 | public void onActionClicked(Action action) {
72 | if (action == mRewindAction) {
73 | rewind();
74 | } else if (action == mFastForwardAction) {
75 | fastForward();
76 | }else {
77 | super.onActionClicked(action);
78 | }
79 | }
80 |
81 | @Override
82 | public void next() {
83 | mActionListener.onNext();
84 | }
85 |
86 | @Override
87 | public void previous() {
88 | mActionListener.onPrevious();
89 | }
90 |
91 | /** Skips backwards 10 seconds. */
92 | public void rewind() {
93 | long newPosition = getCurrentPosition() - TEN_SECONDS;
94 | newPosition = (newPosition < 0) ? 0 : newPosition;
95 | getPlayerAdapter().seekTo(newPosition);
96 | }
97 |
98 | /** Skips forward 10 seconds. */
99 | public void fastForward() {
100 | if (getDuration() > -1) {
101 | long newPosition = getCurrentPosition() + TEN_SECONDS;
102 | newPosition = (newPosition > getDuration()) ? getDuration() : newPosition;
103 | getPlayerAdapter().seekTo(newPosition);
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/presenter/CardPresenter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.presenter;
17 |
18 | import android.graphics.drawable.Drawable;
19 |
20 | import androidx.leanback.widget.ImageCardView;
21 | import androidx.leanback.widget.Presenter;
22 | import androidx.core.content.ContextCompat;
23 |
24 | import android.util.Log;
25 | import android.view.ViewGroup;
26 |
27 | import com.bumptech.glide.Glide;
28 | import com.google.sample.cast.atvreceiver.data.Movie;
29 | import com.google.sample.cast.atvreceiver.R;
30 | /**
31 | * A CardPresenter is used to generate Views and bind Objects to them on demand.
32 | * It contains an Image CardView
33 | */
34 | public class CardPresenter extends Presenter {
35 | private static final String TAG = "CardPresenter";
36 |
37 | private static final int CARD_WIDTH = 313;
38 | private static final int CARD_HEIGHT = 176;
39 | private static int sSelectedBackgroundColor;
40 | private static int sDefaultBackgroundColor;
41 | private Drawable mDefaultCardImage;
42 |
43 | private static void updateCardBackgroundColor(ImageCardView view, boolean selected) {
44 | int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor;
45 | // Both background colors should be set because the view's background is temporarily visible
46 | // during animations.
47 | view.setBackgroundColor(color);
48 | view.findViewById(R.id.info_field).setBackgroundColor(color);
49 | }
50 |
51 | @Override
52 | public ViewHolder onCreateViewHolder(ViewGroup parent) {
53 | Log.d(TAG, "onCreateViewHolder");
54 |
55 | sDefaultBackgroundColor =
56 | ContextCompat.getColor(parent.getContext(), R.color.default_background);
57 | sSelectedBackgroundColor =
58 | ContextCompat.getColor(parent.getContext(), R.color.selected_background);
59 | /*
60 | * This template uses a default image in res/drawable, but the general case for Android TV
61 | * will require your resources in xhdpi. For more information, see
62 | * https://developer.android.com/training/tv/start/layouts.html#density-resources
63 | */
64 | mDefaultCardImage = ContextCompat.getDrawable(parent.getContext(), R.drawable.movie);
65 |
66 | ImageCardView cardView =
67 | new ImageCardView(parent.getContext()) {
68 | @Override
69 | public void setSelected(boolean selected) {
70 | updateCardBackgroundColor(this, selected);
71 | super.setSelected(selected);
72 | }
73 | };
74 |
75 | cardView.setFocusable(true);
76 | cardView.setFocusableInTouchMode(true);
77 | updateCardBackgroundColor(cardView, false);
78 | return new ViewHolder(cardView);
79 | }
80 |
81 | @Override
82 | public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
83 | Movie movie = (Movie) item;
84 | ImageCardView cardView = (ImageCardView) viewHolder.view;
85 |
86 | Log.d(TAG, "onBindViewHolder");
87 | if (movie.getCardImageUrl() != null) {
88 | cardView.setTitleText(movie.getTitle());
89 | cardView.setContentText(movie.getStudio());
90 | cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT);
91 | Glide.with(viewHolder.view.getContext())
92 | .load(movie.getCardImageUrl())
93 | .centerCrop()
94 | .error(mDefaultCardImage)
95 | .into(cardView.getMainImageView());
96 | }
97 | }
98 |
99 | @Override
100 | public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {
101 | Log.d(TAG, "onUnbindViewHolder");
102 | ImageCardView cardView = (ImageCardView) viewHolder.view;
103 | // Remove references to images so that the garbage collector can free up memory
104 | cardView.setBadgeImage(null);
105 | cardView.setMainImage(null);
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/data/MovieList.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.sample.cast.atvreceiver.data;
18 |
19 | import android.util.Log;
20 |
21 | import org.json.JSONArray;
22 | import org.json.JSONException;
23 | import org.json.JSONObject;
24 |
25 | import java.io.BufferedInputStream;
26 | import java.io.BufferedReader;
27 | import java.io.IOException;
28 | import java.io.InputStream;
29 | import java.io.InputStreamReader;
30 | import java.net.URLConnection;
31 | import java.util.ArrayList;
32 | import java.util.HashMap;
33 | import java.util.List;
34 | import java.util.Map;
35 |
36 |
37 | public final class MovieList {
38 | private static final String TAG = "MovieList";
39 |
40 | private static final String TAG_VIDEOS = "videos";
41 | private static final String TAG_HLS = "hls";
42 | private static final String TAG_DASH = "dash";
43 | private static final String TAG_MP4 = "mp4";
44 | private static final String TAG_IMAGES = "images";
45 | private static final String TAG_VIDEO_TYPE = "type";
46 | private static final String TAG_VIDEO_URL = "url";
47 | private static final String TAG_VIDEO_MIME = "mime";
48 |
49 | private static final String TAG_CATEGORIES = "categories";
50 | private static final String TAG_NAME = "name";
51 | private static final String TAG_STUDIO = "studio";
52 | private static final String TAG_SOURCES = "sources";
53 | private static final String TAG_SUBTITLE = "subtitle";
54 | private static final String TAG_DURATION = "duration";
55 | private static final String TAG_THUMB = "image-480x270"; // "thumb";
56 | private static final String TAG_IMG_780_1200 = "image-780x1200";
57 | private static final String TAG_TITLE = "title";
58 | private static final String TARGET_FORMAT = TAG_HLS;
59 |
60 | public static final String MOVIE_CATEGORY[] = {
61 | "VOD",
62 | "Playlist",
63 | "Ads",
64 | "Live"
65 | };
66 |
67 | private static List list;
68 | private static int count = 0;
69 |
70 | public static List getList() {
71 | return list;
72 | }
73 |
74 | protected JSONObject parseUrl(String urlString) {
75 | InputStream is = null;
76 | try {
77 | java.net.URL url = new java.net.URL(urlString);
78 | URLConnection urlConnection = url.openConnection();
79 | is = new BufferedInputStream(urlConnection.getInputStream());
80 | BufferedReader reader = new BufferedReader(new InputStreamReader(
81 | urlConnection.getInputStream(), "iso-8859-1"), 1024);
82 | StringBuilder sb = new StringBuilder();
83 | String line;
84 | while ((line = reader.readLine()) != null) {
85 | sb.append(line);
86 | }
87 | String json = sb.toString();
88 | return new JSONObject(json);
89 | } catch (Exception e) {
90 | Log.d(TAG, "Failed to parse the json for media list", e);
91 | return null;
92 | } finally {
93 | if (null != is) {
94 | try {
95 | is.close();
96 | } catch (IOException e) {
97 | // ignore
98 | }
99 | }
100 | }
101 | }
102 |
103 | public static List setupMovies(String url) throws JSONException {
104 | if (null != list) {
105 | return list;
106 | }
107 | list = new ArrayList<>();
108 |
109 | Map urlPrefixMap = new HashMap<>();
110 | JSONObject jsonObj = new MovieList().parseUrl(url);
111 | JSONArray categories = jsonObj.getJSONArray(TAG_CATEGORIES);
112 | if (null != categories) {
113 | for (int i = 0; i < categories.length(); i++) {
114 | JSONObject category = categories.getJSONObject(i);
115 | urlPrefixMap.put(TAG_HLS, category.getString(TAG_HLS));
116 | urlPrefixMap.put(TAG_DASH, category.getString(TAG_DASH));
117 | urlPrefixMap.put(TAG_MP4, category.getString(TAG_MP4));
118 | urlPrefixMap.put(TAG_IMAGES, category.getString(TAG_IMAGES));
119 | category.getString(TAG_NAME);
120 | JSONArray videos = category.getJSONArray(TAG_VIDEOS);
121 | if (null != videos) {
122 | for (int j = 0; j < videos.length(); j++) {
123 | String videoUrl = null;
124 | String mimeType = null;
125 | JSONObject video = videos.getJSONObject(j);
126 | String subTitle = video.getString(TAG_SUBTITLE);
127 | JSONArray videoSpecs = video.getJSONArray(TAG_SOURCES);
128 | if (null == videoSpecs || videoSpecs.length() == 0) {
129 | continue;
130 | }
131 | for (int k = 0; k < videoSpecs.length(); k++) {
132 | JSONObject videoSpec = videoSpecs.getJSONObject(k);
133 | if (TARGET_FORMAT.equals(videoSpec.getString(TAG_VIDEO_TYPE))) {
134 | videoUrl = urlPrefixMap.get(TARGET_FORMAT) + videoSpec
135 | .getString(TAG_VIDEO_URL);
136 | mimeType = videoSpec.getString(TAG_VIDEO_MIME);
137 | }
138 | }
139 | if (videoUrl == null) {
140 | continue;
141 | }
142 | String imageUrl = urlPrefixMap.get(TAG_IMAGES) + video.getString(TAG_THUMB);
143 | String bigImageUrl = urlPrefixMap.get(TAG_IMAGES) + video
144 | .getString(TAG_IMG_780_1200);
145 | String title = video.getString(TAG_TITLE);
146 | String studio = video.getString(TAG_STUDIO);
147 | long duration = video.getInt(TAG_DURATION) * 1000;
148 | list.add(buildMovieInfo(
149 | title, subTitle, studio, videoUrl, imageUrl, bigImageUrl));
150 | }
151 | }
152 | }
153 | }
154 |
155 | return list;
156 | }
157 |
158 | private static Movie buildMovieInfo(
159 | String title,
160 | String description,
161 | String studio,
162 | String videoUrl,
163 | String cardImageUrl,
164 | String backgroundImageUrl) {
165 | Movie movie = new Movie();
166 | movie.setId(count++);
167 | movie.setTitle(title);
168 | movie.setDescription(description);
169 | movie.setStudio(studio);
170 | movie.setCardImageUrl(cardImageUrl);
171 | movie.setBackgroundImageUrl(backgroundImageUrl);
172 | movie.setVideoUrl(videoUrl);
173 | return movie;
174 | }
175 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/ui/MainFragment.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.ui;
17 |
18 | import android.app.LoaderManager;
19 | import android.content.Intent;
20 | import android.content.Loader;
21 | import android.graphics.drawable.Drawable;
22 | import android.os.Bundle;
23 | import android.os.Handler;
24 | import android.util.DisplayMetrics;
25 | import android.util.Log;
26 | import android.view.View;
27 | import android.widget.Toast;
28 |
29 | import androidx.core.content.ContextCompat;
30 | import androidx.leanback.app.BackgroundManager;
31 | import androidx.leanback.app.BrowseFragment;
32 | import androidx.leanback.widget.ArrayObjectAdapter;
33 | import androidx.leanback.widget.HeaderItem;
34 | import androidx.leanback.widget.ListRow;
35 | import androidx.leanback.widget.ListRowPresenter;
36 | import androidx.leanback.widget.OnItemViewClickedListener;
37 | import androidx.leanback.widget.OnItemViewSelectedListener;
38 | import androidx.leanback.widget.Presenter;
39 | import androidx.leanback.widget.Row;
40 | import androidx.leanback.widget.RowPresenter;
41 |
42 | import com.bumptech.glide.Glide;
43 | import com.bumptech.glide.request.target.SimpleTarget;
44 | import com.bumptech.glide.request.transition.Transition;
45 | import com.google.sample.cast.atvreceiver.R;
46 | import com.google.sample.cast.atvreceiver.data.Movie;
47 | import com.google.sample.cast.atvreceiver.data.MovieList;
48 | import com.google.sample.cast.atvreceiver.data.MovieListLoader;
49 | import com.google.sample.cast.atvreceiver.presenter.CardPresenter;
50 |
51 | import java.util.Collections;
52 | import java.util.List;
53 | import java.util.Timer;
54 | import java.util.TimerTask;
55 |
56 | public class MainFragment extends BrowseFragment implements LoaderManager.LoaderCallbacks> {
57 | private static final String TAG = "MainFragment";
58 |
59 | private static final int BACKGROUND_UPDATE_DELAY = 300;
60 |
61 | private final Handler mHandler = new Handler();
62 | private Drawable mDefaultBackground;
63 | private DisplayMetrics mMetrics;
64 | private Timer mBackgroundTimer;
65 | private String mBackgroundUri;
66 | private BackgroundManager mBackgroundManager;
67 | private ArrayObjectAdapter mCategoryRowAdapter;
68 |
69 | @Override
70 | public void onActivityCreated(Bundle savedInstanceState) {
71 | Log.i(TAG, "onCreate");
72 | super.onActivityCreated(savedInstanceState);
73 |
74 | getLoaderManager().initLoader(0, null, this);
75 |
76 | prepareBackgroundManager();
77 |
78 | setupUIElements();
79 |
80 | mCategoryRowAdapter = new ArrayObjectAdapter(new ListRowPresenter());
81 | setAdapter(mCategoryRowAdapter);
82 |
83 | setupEventListeners();
84 | }
85 |
86 | @Override
87 | public void onDestroy() {
88 | super.onDestroy();
89 | if (null != mBackgroundTimer) {
90 | Log.d(TAG, "onDestroy: " + mBackgroundTimer.toString());
91 | mBackgroundTimer.cancel();
92 | }
93 | }
94 |
95 | private void prepareBackgroundManager() {
96 |
97 | mBackgroundManager = BackgroundManager.getInstance(getActivity());
98 | mBackgroundManager.attach(getActivity().getWindow());
99 |
100 | mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background);
101 | mMetrics = new DisplayMetrics();
102 | getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
103 | }
104 |
105 | private void setupUIElements() {
106 | setTitle(getString(R.string.browse_title));
107 | setHeadersState(HEADERS_ENABLED);
108 | setHeadersTransitionOnBackEnabled(true);
109 |
110 | // set fastLane (or headers) background color
111 | setBrandColor(ContextCompat.getColor(getActivity(), R.color.fastlane_background));
112 | // set search icon color
113 | setSearchAffordanceColor(ContextCompat.getColor(getActivity(), R.color.search_opaque));
114 | }
115 |
116 | private void setupEventListeners() {
117 | setOnSearchClickedListener(new View.OnClickListener() {
118 |
119 | @Override
120 | public void onClick(View view) {
121 | Toast.makeText(getActivity(), "Implement your own in-app search", Toast.LENGTH_LONG)
122 | .show();
123 | }
124 | });
125 |
126 | setOnItemViewClickedListener(new ItemViewClickedListener());
127 | setOnItemViewSelectedListener(new ItemViewSelectedListener());
128 | }
129 |
130 | private void updateBackground(String uri) {
131 | int width = mMetrics.widthPixels;
132 | int height = mMetrics.heightPixels;
133 | Glide.with(getActivity())
134 | .load(uri)
135 | .centerCrop()
136 | .error(mDefaultBackground)
137 | .into(new SimpleTarget(width, height) {
138 | @Override
139 | public void onResourceReady(Drawable resource,
140 | Transition super Drawable> transition) {
141 | mBackgroundManager.setDrawable(resource);
142 | }
143 | });
144 | mBackgroundTimer.cancel();
145 | }
146 |
147 | private void startBackgroundTimer() {
148 | if (null != mBackgroundTimer) {
149 | mBackgroundTimer.cancel();
150 | }
151 | mBackgroundTimer = new Timer();
152 | mBackgroundTimer.schedule(new UpdateBackgroundTask(), BACKGROUND_UPDATE_DELAY);
153 | }
154 |
155 | @Override
156 | public Loader> onCreateLoader(int id, Bundle args) {
157 | return new MovieListLoader(getActivity(), getString(R.string.catalog_url));
158 | }
159 |
160 | @Override
161 | public void onLoadFinished(Loader> loader, List data) {
162 | CardPresenter cardPresenter = new CardPresenter();
163 |
164 | int i;
165 | for (i = 0; i < MovieList.MOVIE_CATEGORY.length; i++) {
166 | if (i != 0) {
167 | Collections.shuffle(data);
168 | }
169 | ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter);
170 | for (int j = 0; j < data.size(); j++) {
171 | listRowAdapter.add(data.get(j));
172 | }
173 | HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i]);
174 | mCategoryRowAdapter.add(new ListRow(header, listRowAdapter));
175 | }
176 | }
177 |
178 | @Override
179 | public void onLoaderReset(Loader> loader) {
180 | mCategoryRowAdapter.clear();
181 | }
182 |
183 | private final class ItemViewClickedListener implements OnItemViewClickedListener {
184 | @Override
185 | public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
186 | RowPresenter.ViewHolder rowViewHolder, Row row) {
187 |
188 | if (item instanceof Movie) {
189 | Movie movie = (Movie) item;
190 | Log.d(TAG, "Item: " + item.toString());
191 | Intent intent = new Intent(getActivity(), PlaybackActivity.class);
192 | intent.putExtra(MainActivity.MOVIE, movie);
193 | startActivity(intent);
194 | }
195 | }
196 | }
197 |
198 | private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
199 | @Override
200 | public void onItemSelected(
201 | Presenter.ViewHolder itemViewHolder,
202 | Object item,
203 | RowPresenter.ViewHolder rowViewHolder,
204 | Row row) {
205 | if (item instanceof Movie) {
206 | mBackgroundUri = ((Movie) item).getBackgroundImageUrl();
207 | startBackgroundTimer();
208 | }
209 | }
210 | }
211 |
212 | private class UpdateBackgroundTask extends TimerTask {
213 |
214 | @Override
215 | public void run() {
216 | mHandler.post(new Runnable() {
217 | @Override
218 | public void run() {
219 | updateBackground(mBackgroundUri);
220 | }
221 | });
222 | }
223 | }
224 |
225 | }
226 |
--------------------------------------------------------------------------------
/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 2020 Google LLC
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 |
203 |
--------------------------------------------------------------------------------
/app/src/main/java/com/google/sample/cast/atvreceiver/ui/PlaybackVideoFragment.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google LLC. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.sample.cast.atvreceiver.ui;
17 |
18 | import android.content.Intent;
19 | import android.net.Uri;
20 | import android.os.Bundle;
21 | import android.support.v4.media.MediaMetadataCompat;
22 | import android.support.v4.media.session.MediaSessionCompat;
23 | import android.util.Log;
24 | import android.widget.Toast;
25 | import androidx.leanback.app.VideoSupportFragment;
26 | import androidx.leanback.app.VideoSupportFragmentGlueHost;
27 | import androidx.leanback.widget.PlaybackControlsRow;
28 | import com.google.android.exoplayer2.ExoPlayerFactory;
29 | import com.google.android.exoplayer2.Player;
30 | import com.google.android.exoplayer2.SimpleExoPlayer;
31 | import com.google.android.exoplayer2.ext.leanback.LeanbackPlayerAdapter;
32 | import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector;
33 | import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector.MediaMetadataProvider;
34 | import com.google.android.exoplayer2.source.MediaSource;
35 | import com.google.android.exoplayer2.source.ProgressiveMediaSource;
36 | import com.google.android.exoplayer2.source.hls.HlsMediaSource;
37 | import com.google.android.exoplayer2.upstream.DataSource;
38 | import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
39 | import com.google.android.exoplayer2.util.Util;
40 | import com.google.android.gms.cast.MediaError;
41 | import com.google.android.gms.cast.MediaError.DetailedErrorCode;
42 | import com.google.android.gms.cast.MediaInfo;
43 | import com.google.android.gms.cast.MediaLoadRequestData;
44 | import com.google.android.gms.cast.MediaMetadata;
45 | import com.google.android.gms.cast.tv.CastReceiverContext;
46 | import com.google.android.gms.cast.tv.media.MediaException;
47 | import com.google.android.gms.cast.tv.media.MediaInfoWriter;
48 | import com.google.android.gms.cast.tv.media.MediaLoadCommandCallback;
49 | import com.google.android.gms.cast.tv.media.MediaManager;
50 | import com.google.android.gms.cast.tv.media.MediaManager.MediaStatusInterceptor;
51 | import com.google.android.gms.cast.tv.media.MediaStatusWriter;
52 | import com.google.android.gms.common.images.WebImage;
53 | import com.google.android.gms.tasks.Task;
54 | import com.google.android.gms.tasks.Tasks;
55 | import com.google.sample.cast.atvreceiver.R;
56 | import com.google.sample.cast.atvreceiver.data.Movie;
57 | import com.google.sample.cast.atvreceiver.data.MovieList;
58 | import com.google.sample.cast.atvreceiver.player.VideoPlayerGlue;
59 | import java.util.List;
60 | import org.json.JSONException;
61 | import org.json.JSONObject;
62 |
63 | /**
64 | * Handles video playback with media controls.
65 | */
66 | public class PlaybackVideoFragment extends VideoSupportFragment {
67 |
68 | private static final String LOG_TAG = "PlaybackVideoFragment";
69 | private static final int UPDATE_DELAY = 16;
70 |
71 | private MediaSessionCompat mMediaSession;
72 | private MediaSessionConnector mMediaSessionConnector;
73 |
74 | private SimpleExoPlayer mPlayer;
75 | private LeanbackPlayerAdapter mPlayerAdapter;
76 | private VideoPlayerGlue mPlayerGlue;
77 | private PlaylistActionListener mPlaylistActionListener;
78 | private MyMediaMetadataProvider mMediaMetadataProvider;
79 | private Movie playingMovie;
80 |
81 | private MediaManager mMediaManager;
82 |
83 | private static final String TYPE_HLS = "application/x-mpegurl";
84 | private static final String TYPE_MP4 = "video/mp4";
85 | private static String type;
86 |
87 | @Override
88 | public void onCreate(Bundle savedInstanceState) {
89 | super.onCreate(savedInstanceState);
90 | Log.d(LOG_TAG, "onCreate");
91 |
92 | mMediaSession = new MediaSessionCompat(getContext(), LOG_TAG);
93 | mMediaSessionConnector = new MediaSessionConnector(mMediaSession);
94 | initializePlayer();
95 | }
96 |
97 | @Override
98 | public void onStart() {
99 | super.onStart();
100 | Log.d(LOG_TAG, "onStart");
101 |
102 | mMediaManager = CastReceiverContext.getInstance().getMediaManager();
103 | mMediaManager.setSessionCompatToken(mMediaSession.getSessionToken());
104 | mMediaManager.setMediaLoadCommandCallback(new MyMediaLoadCommandCallback());
105 |
106 | mMediaManager.setMediaStatusInterceptor(new MediaStatusInterceptor() {
107 | @Override
108 | public void intercept(MediaStatusWriter mediaStatusWriter) {
109 | try {
110 | mediaStatusWriter.setCustomData(new JSONObject("{data: 'CustomData'}"));
111 | } catch (JSONException e) {
112 | e.printStackTrace();
113 | }
114 | }
115 | });
116 |
117 | initializePlayer();
118 | mMediaSessionConnector.setPlayer(mPlayer);
119 | mMediaSessionConnector.setMediaMetadataProvider(mMediaMetadataProvider);
120 | mMediaSession.setActive(true);
121 |
122 | if (mMediaManager.onNewIntent(getActivity().getIntent())) {
123 | // If the SDK recognizes the intent, you should early return.
124 | return;
125 | }
126 |
127 | // If the SDK doesn't recognize the intent, you can handle the intent with
128 | // your own logic.
129 | processIntent(getActivity().getIntent());
130 |
131 | }
132 |
133 | @Override
134 | public void onResume() {
135 | super.onResume();
136 | Log.d(LOG_TAG, "onResume");
137 | }
138 |
139 | @Override
140 | public void onPause() {
141 | super.onPause();
142 | Log.d(LOG_TAG, "onPause");
143 | if (mPlayerGlue != null && mPlayerGlue.isPlaying()) {
144 | mPlayerGlue.pause();
145 | }
146 | }
147 |
148 | @Override
149 | public void onStop() {
150 | super.onStop();
151 | Log.d(LOG_TAG, "onStop");
152 |
153 | mMediaSessionConnector.setPlayer(null);
154 | mMediaSession.setActive(false);
155 | mMediaSession.release();
156 | mMediaManager.setSessionCompatToken(null);
157 | releasePlayer();
158 | Intent intent = new Intent(getContext(), MainActivity.class);
159 | startActivity(intent);
160 | }
161 |
162 | @Override
163 | public void onError(int errorCode, CharSequence errorMessage) {
164 | Log.d(LOG_TAG, "onError");
165 | logAndDisplay(errorMessage.toString());
166 | getActivity().finish();
167 | }
168 |
169 | void processIntent(Intent intent) {
170 | Log.d(LOG_TAG, "processIntent()");
171 |
172 | if (intent.hasExtra(MainActivity.MOVIE)) {
173 | // Intent came from MainActivity (User chose an item inside ATV app).
174 | Movie movie = (Movie) intent.getSerializableExtra(MainActivity.MOVIE);
175 | type = TYPE_HLS;
176 | startPlayback(movie, 0);
177 | } else {
178 | logAndDisplay("Null or unrecognized intent action");
179 | getActivity().finish();
180 | }
181 | }
182 |
183 | private static Movie convertEntityToMovie(String entity) {
184 | return MovieList.getList().get(0);
185 | }
186 |
187 | private static Movie convertLoadRequestToMovie(MediaLoadRequestData loadRequestData) {
188 | if (loadRequestData == null) {
189 | return null;
190 | }
191 | MediaInfo mediaInfo = loadRequestData.getMediaInfo();
192 | if (mediaInfo == null) {
193 | return null;
194 | }
195 |
196 | type = mediaInfo.getContentType();
197 |
198 | String videoUrl = mediaInfo.getContentId();
199 | if (mediaInfo.getContentUrl() != null) {
200 | videoUrl = mediaInfo.getContentUrl();
201 | }
202 |
203 | MediaMetadata metadata = mediaInfo.getMetadata();
204 | Movie movie = new Movie();
205 | movie.setVideoUrl(videoUrl);
206 | if (metadata != null) {
207 | movie.setTitle(metadata.getString(MediaMetadata.KEY_TITLE));
208 | movie.setDescription(metadata.getString(MediaMetadata.KEY_SUBTITLE));
209 | movie.setCardImageUrl(metadata.getImages().get(0).getUrl().toString());
210 | }
211 | return movie;
212 | }
213 |
214 | private void initializePlayer() {
215 | if (mPlayer == null) {
216 | Log.d(LOG_TAG, "initializePlayer");
217 | VideoSupportFragmentGlueHost glueHost =
218 | new VideoSupportFragmentGlueHost(PlaybackVideoFragment.this);
219 |
220 | mPlayer = ExoPlayerFactory.newSimpleInstance(getContext());
221 | mPlayerAdapter = new LeanbackPlayerAdapter(getContext(), mPlayer, UPDATE_DELAY);
222 | mPlayerAdapter.setRepeatAction(PlaybackControlsRow.RepeatAction.INDEX_NONE);
223 | mPlaylistActionListener = new PlaylistActionListener();
224 | mMediaMetadataProvider = new MyMediaMetadataProvider();
225 | mPlayerGlue = new VideoPlayerGlue(getContext(), mPlayerAdapter, mPlaylistActionListener);
226 | mPlayerGlue.setHost(glueHost);
227 | mPlayerGlue.setSeekEnabled(true);
228 | }
229 | }
230 |
231 | private void releasePlayer() {
232 | if (mPlayer != null) {
233 | Log.d(LOG_TAG, "releasePlayer");
234 | mPlayer.release();
235 | mPlayer = null;
236 | mPlayerAdapter = null;
237 | }
238 | }
239 |
240 | private void startPlayback(Movie movie, long startPosition) {
241 | playingMovie = movie;
242 | mPlayerGlue.setTitle(movie.getTitle());
243 | mPlayerGlue.setSubtitle(movie.getDescription());
244 | prepareMediaForPlaying(Uri.parse(movie.getVideoUrl()));
245 | mPlayerGlue.playWhenPrepared();
246 | mMediaManager.getMediaStatusModifier().clear();
247 | }
248 |
249 | private void prepareMediaForPlaying(Uri mediaSourceUri) {
250 | DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(
251 | getContext(), Util.getUserAgent(getContext(), getString(R.string.app_name)));
252 |
253 | MediaSource mediaSource;
254 | switch (type) {
255 | case TYPE_HLS:
256 | mediaSource = new HlsMediaSource.Factory(dataSourceFactory)
257 | .createMediaSource(mediaSourceUri);
258 | break;
259 |
260 | case TYPE_MP4:
261 | mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
262 | .createMediaSource(mediaSourceUri);
263 | break;
264 |
265 | default:
266 | mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
267 | .createMediaSource(mediaSourceUri);
268 | Log.d(LOG_TAG, "Unrecognized MediaSource");
269 | }
270 | mPlayer.prepare(mediaSource);
271 | }
272 |
273 | private void logAndDisplay(String error) {
274 | Log.d(LOG_TAG, error);
275 | Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
276 | }
277 |
278 | class PlaylistActionListener implements VideoPlayerGlue.OnActionClickedListener {
279 |
280 | private List mPlaylist;
281 |
282 | PlaylistActionListener() {
283 | this.mPlaylist = MovieList.getList();
284 | }
285 |
286 | @Override
287 | public void onPrevious() {
288 | int currentIndex = playingMovie.getId();
289 | if (currentIndex - 1 >= 0) {
290 | startPlayback(mPlaylist.get(currentIndex - 1),0);
291 | }
292 | }
293 |
294 | @Override
295 | public void onNext() {
296 | int currentIndex = playingMovie.getId();
297 | if (currentIndex + 1 < mPlaylist.size()) {
298 | startPlayback(mPlaylist.get(currentIndex + 1), 0);
299 | }
300 | }
301 | }
302 |
303 | class MyMediaMetadataProvider implements MediaMetadataProvider {
304 | @Override
305 | public MediaMetadataCompat getMetadata(Player player) {
306 | MediaMetadataCompat.Builder mediaMetadata = new MediaMetadataCompat.Builder();
307 | if (playingMovie != null) {
308 | mediaMetadata.putString(
309 | MediaMetadataCompat.METADATA_KEY_TITLE, playingMovie.getTitle());
310 | mediaMetadata.putString(
311 | MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, playingMovie.getTitle());
312 | mediaMetadata.putString(
313 | MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE,
314 | playingMovie.getDescription());
315 | mediaMetadata.putString(
316 | MediaMetadataCompat.METADATA_KEY_MEDIA_URI, playingMovie.getVideoUrl());
317 | mediaMetadata.putString(
318 | MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI,
319 | playingMovie.getCardImageUrl());
320 | }
321 | mediaMetadata.putLong(
322 | MediaMetadataCompat.METADATA_KEY_DURATION, mPlayerGlue.getDuration());
323 |
324 | return mediaMetadata.build();
325 | }
326 | }
327 |
328 | private void myFillMediaInfo(MediaInfoWriter mediaInfoWriter) {
329 | MediaInfo mediaInfo = mediaInfoWriter.getMediaInfo();
330 | Log.d(LOG_TAG,"***Type:"+mediaInfo.getContentType());
331 | if (mediaInfo.getContentUrl() == null && mediaInfo.getEntity() != null) {
332 | // Load By Entity
333 | String entity = mediaInfo.getEntity();
334 | Movie movie = convertEntityToMovie(entity);
335 |
336 | MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
337 | movieMetadata.putString(MediaMetadata.KEY_TITLE, movie.getTitle());
338 | movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, movie.getDescription());
339 | movieMetadata.putString(MediaMetadata.KEY_STUDIO, movie.getStudio());
340 | movieMetadata.addImage(new WebImage(Uri.parse(movie.getCardImageUrl())));
341 | movieMetadata.addImage(new WebImage(Uri.parse(movie.getBackgroundImageUrl())));
342 |
343 | mediaInfoWriter.setContentUrl(movie.getVideoUrl()).setMetadata(movieMetadata);
344 | }
345 | }
346 |
347 | class MyMediaLoadCommandCallback extends MediaLoadCommandCallback {
348 | @Override
349 | public Task onLoad(String senderId, MediaLoadRequestData loadRequestData) {
350 | Toast.makeText(getActivity(), "onLoad()", Toast.LENGTH_SHORT).show();
351 |
352 | if (loadRequestData == null) {
353 | // Throw MediaException to indicate load failure.
354 | return Tasks.forException(new MediaException(
355 | new MediaError.Builder()
356 | .setDetailedErrorCode(DetailedErrorCode.LOAD_FAILED)
357 | .setReason(MediaError.ERROR_REASON_INVALID_REQUEST)
358 | .build()));
359 | }
360 |
361 | return Tasks.call(() -> {
362 | // Resolve the entity into your data structure and load media.
363 | myFillMediaInfo(new MediaInfoWriter(loadRequestData.getMediaInfo()));
364 | startPlayback(convertLoadRequestToMovie(loadRequestData), 0);
365 |
366 | // Update media metadata and state (this clears all previous status
367 | // overrides).
368 | mMediaManager.setDataFromLoad(loadRequestData);
369 | mMediaManager.broadcastMediaStatus();
370 |
371 | return loadRequestData;
372 | });
373 | }
374 | }
375 | }
--------------------------------------------------------------------------------