├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── Application
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ ├── tile.9.png
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_menu_add.png
│ │ │ ├── ic_action_play.png
│ │ │ ├── ic_action_stop.png
│ │ │ ├── ic_media_pause.png
│ │ │ ├── ic_media_play.png
│ │ │ ├── ic_media_stop.png
│ │ │ ├── ic_menu_delete.png
│ │ │ └── ic_action_pause.png
│ │ ├── drawable-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_menu_add.png
│ │ │ ├── ic_action_play.png
│ │ │ ├── ic_action_stop.png
│ │ │ ├── ic_media_pause.png
│ │ │ ├── ic_media_play.png
│ │ │ ├── ic_media_stop.png
│ │ │ ├── ic_menu_delete.png
│ │ │ └── ic_action_pause.png
│ │ ├── drawable-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_action_pause.png
│ │ │ ├── ic_action_play.png
│ │ │ └── ic_action_stop.png
│ │ ├── drawable-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_action_play.png
│ │ │ ├── ic_action_stop.png
│ │ │ ├── ic_action_pause.png
│ │ │ ├── ic_suggestions_add.png
│ │ │ └── ic_suggestions_delete.png
│ │ ├── drawable
│ │ │ └── list_background.xml
│ │ ├── values-v21
│ │ │ ├── base-colors.xml
│ │ │ └── base-template-styles.xml
│ │ ├── values-v11
│ │ │ └── template-styles.xml
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── base-strings.xml
│ │ │ ├── template-dimens.xml
│ │ │ ├── arrays.xml
│ │ │ ├── template-styles.xml
│ │ │ └── strings.xml
│ │ ├── values-sw600dp
│ │ │ ├── template-dimens.xml
│ │ │ └── template-styles.xml
│ │ ├── menu
│ │ │ └── sample_media_router_menu.xml
│ │ └── layout
│ │ │ ├── overlay_display_window.xml
│ │ │ ├── sample_media_router_presentation.xml
│ │ │ ├── media_item.xml
│ │ │ └── sample_media_router.xml
│ │ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── android
│ │ │ ├── mediarouter
│ │ │ ├── provider
│ │ │ │ ├── SampleMediaRouteProviderService.java
│ │ │ │ └── SampleMediaRouteProvider.java
│ │ │ └── player
│ │ │ │ ├── SampleMediaButtonReceiver.java
│ │ │ │ ├── Player.java
│ │ │ │ ├── PlaylistItem.java
│ │ │ │ ├── SessionManager.java
│ │ │ │ ├── RemotePlayer.java
│ │ │ │ ├── OverlayDisplayWindow.java
│ │ │ │ └── LocalPlayer.java
│ │ │ └── common
│ │ │ └── logger
│ │ │ ├── LogNode.java
│ │ │ ├── MessageOnlyLogFilter.java
│ │ │ ├── LogWrapper.java
│ │ │ ├── LogFragment.java
│ │ │ ├── LogView.java
│ │ │ └── Log.java
│ │ └── AndroidManifest.xml
├── build.gradle
└── tests
│ ├── AndroidManifest.xml
│ └── src
│ └── com
│ └── example
│ └── android
│ └── mediarouter
│ └── tests
│ └── SampleTests.java
├── README.md
├── .google
└── packaging.yaml
├── packaging.yaml
├── CONTRIBUTING.md
├── CONTRIB.md
├── gradlew.bat
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | include 'Application'
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/tile.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/tile.9.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_menu_add.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_menu_add.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_menu_add.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_menu_add.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_action_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_action_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_action_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_action_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_media_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_media_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_media_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_media_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_media_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_media_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_menu_delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_menu_delete.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_action_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_action_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_action_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_action_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_media_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_media_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_media_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_media_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_media_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_media_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_menu_delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_menu_delete.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_action_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-hdpi/ic_action_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_action_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-mdpi/ic_action_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xhdpi/ic_action_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xhdpi/ic_action_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xhdpi/ic_action_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xhdpi/ic_action_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xhdpi/ic_action_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xhdpi/ic_action_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_action_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_action_play.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_action_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_action_stop.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_action_pause.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_action_pause.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_suggestions_add.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_suggestions_add.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_suggestions_delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-MediaRouter/HEAD/Application/src/main/res/drawable-xxhdpi/ic_suggestions_delete.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Android MediaRouter Sample
3 | ==========================
4 |
5 | This repo has been migrated to [github.com/android/media-samples][1]. Please check that repo for future updates. Thank you!
6 |
7 | [1]: https://github.com/android/media-samples
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Sep 28 17:54:49 JST 2016
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
--------------------------------------------------------------------------------
/Application/src/main/res/drawable/list_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
7 |
8 |
--------------------------------------------------------------------------------
/.google/packaging.yaml:
--------------------------------------------------------------------------------
1 |
2 | # GOOGLE SAMPLE PACKAGING DATA
3 | #
4 | # This file is used by Google as part of our samples packaging process.
5 | # End users may safely ignore this file. It has no relevance to other systems.
6 | ---
7 | status: PUBLISHED
8 | technologies: [Android]
9 | categories: [Media]
10 | languages: [Java]
11 | solutions: [Mobile]
12 | github: android-MediaRouter
13 | license: apache2
14 |
--------------------------------------------------------------------------------
/packaging.yaml:
--------------------------------------------------------------------------------
1 | # GOOGLE SAMPLE PACKAGING DATA
2 | #
3 | # This file is used by Google as part of our samples packaging process.
4 | # End users may safely ignore this file. It has no relevance to other systems.
5 | ---
6 |
7 | status: PUBLISHED
8 | technologies: [Android]
9 | categories: [NoGroup]
10 | languages: [Java]
11 | solutions: [Mobile]
12 | github: googlesamples/android-MediaRouter
13 | level: BEGINNER
14 | icon: MediaRouterSample/src/main/res/drawable-xxhdpi/ic_launcher.png
15 | license: apache2-android
16 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-v21/base-colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-v11/template-styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
18 | #770000ff
19 | #ccc
20 |
21 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-v21/base-template-styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-sw600dp/template-dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 | @dimen/margin_huge
22 | @dimen/margin_medium
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/base-strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | MediaRouter
20 |
21 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-sw600dp/template-styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Application/src/main/res/menu/sample_media_router_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
24 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/template-dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 | 4dp
22 | 8dp
23 | 16dp
24 | 32dp
25 | 64dp
26 |
27 |
28 |
29 | @dimen/margin_medium
30 | @dimen/margin_medium
31 |
32 |
33 |
--------------------------------------------------------------------------------
/Application/src/main/res/layout/overlay_display_window.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
21 |
24 |
28 |
29 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/arrays.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
18 |
19 | - Big Buck Bunny
20 | - Elephants Dream
21 | - Sintel
22 | - Tears of Steel
23 |
24 |
25 |
26 | - http://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4
27 | - http://archive.org/download/ElephantsDream_277/elephant_dreams_640_512kb.mp4
28 | - http://archive.org/download/Sintel/sintel-2048-stereo_512kb.mp4
29 | - http://archive.org/download/Tears-of-Steel/tears_of_steel_720p.mp4
30 |
31 |
32 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/provider/SampleMediaRouteProviderService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.provider;
18 |
19 | import android.support.v7.media.MediaRouteProvider;
20 | import android.support.v7.media.MediaRouteProviderService;
21 |
22 | import com.example.android.mediarouter.provider.SampleMediaRouteProvider;
23 |
24 | /**
25 | * Demonstrates how to register a custom media route provider service
26 | * using the support library.
27 | *
28 | * @see com.example.android.mediarouter.provider.SampleMediaRouteProvider
29 | */
30 | public class SampleMediaRouteProviderService extends MediaRouteProviderService {
31 | @Override
32 | public MediaRouteProvider onCreateMediaRouteProvider() {
33 | return new SampleMediaRouteProvider(this);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/template-styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
34 |
35 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/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 (CLA).
9 |
10 | * If you are an individual writing original source code and you're sure you
11 | own the intellectual property, then you'll need to sign an [individual CLA]
12 | (https://cla.developers.google.com).
13 | * If you work for a company that wants to allow you to contribute your work,
14 | then you'll need to sign a [corporate CLA]
15 | (https://cla.developers.google.com).
16 |
17 | Follow either of the two links above to access the appropriate CLA and
18 | instructions for how to sign and return it. Once we receive it, we'll be able to
19 | accept your pull requests.
20 |
21 | ## Contributing A Patch
22 |
23 | 1. Submit an issue describing your proposed change to the repo in question.
24 | 1. The repo owner will respond to your issue promptly.
25 | 1. If your proposed change is accepted, and you haven't already done so, sign a
26 | Contributor License Agreement (see details above).
27 | 1. Fork the desired repo, develop and test your code changes.
28 | 1. Ensure that your code adheres to the existing style in the sample to which
29 | you are contributing. Refer to the
30 | [Android Code Style Guide]
31 | (https://source.android.com/source/code-style.html) for the
32 | recommended coding standards for this organization.
33 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
34 | 1. Submit a pull request.
35 |
36 |
--------------------------------------------------------------------------------
/CONTRIB.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 (CLA).
9 |
10 | * If you are an individual writing original source code and you're sure you
11 | own the intellectual property, then you'll need to sign an [individual CLA]
12 | (https://developers.google.com/open-source/cla/individual).
13 | * If you work for a company that wants to allow you to contribute your work,
14 | then you'll need to sign a [corporate CLA]
15 | (https://developers.google.com/open-source/cla/corporate).
16 |
17 | Follow either of the two links above to access the appropriate CLA and
18 | instructions for how to sign and return it. Once we receive it, we'll be able to
19 | accept your pull requests.
20 |
21 | ## Contributing A Patch
22 |
23 | 1. Submit an issue describing your proposed change to the repo in question.
24 | 1. The repo owner will respond to your issue promptly.
25 | 1. If your proposed change is accepted, and you haven't already done so, sign a
26 | Contributor License Agreement (see details above).
27 | 1. Fork the desired repo, develop and test your code changes.
28 | 1. Ensure that your code adheres to the existing style in the sample to which
29 | you are contributing. Refer to the
30 | [Android Code Style Guide]
31 | (https://source.android.com/source/code-style.html) for the
32 | recommended coding standards for this organization.
33 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
34 | 1. Submit a pull request.
35 |
36 |
--------------------------------------------------------------------------------
/Application/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | buildscript {
3 | repositories {
4 | jcenter()
5 | google()
6 | }
7 |
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:3.0.1'
10 | }
11 | }
12 |
13 | apply plugin: 'com.android.application'
14 |
15 | repositories {
16 | jcenter()
17 | google()
18 | }
19 |
20 | dependencies {
21 | compile "com.android.support:support-v4:27.0.2"
22 | compile "com.android.support:support-v13:27.0.2"
23 | compile "com.android.support:cardview-v7:27.0.2"
24 | compile "com.android.support:appcompat-v7:27.0.2"
25 | compile 'com.android.support:mediarouter-v7:24.2.1'
26 | }
27 |
28 | // The sample build uses multiple directories to
29 | // keep boilerplate and common code separate from
30 | // the main sample code.
31 | List dirs = [
32 | 'main', // main sample code; look here for the interesting stuff.
33 | 'common', // components that are reused by multiple samples
34 | 'template'] // boilerplate code that is generated by the sample template process
35 |
36 | android {
37 | compileSdkVersion 27
38 |
39 | buildToolsVersion "27.0.2"
40 |
41 | defaultConfig {
42 | minSdkVersion 17
43 | targetSdkVersion 27
44 | }
45 |
46 | compileOptions {
47 | sourceCompatibility JavaVersion.VERSION_1_7
48 | targetCompatibility JavaVersion.VERSION_1_7
49 | }
50 |
51 | sourceSets {
52 | main {
53 | dirs.each { dir ->
54 | java.srcDirs "src/${dir}/java"
55 | res.srcDirs "src/${dir}/res"
56 | }
57 | }
58 | androidTest.setRoot('tests')
59 | androidTest.java.srcDirs = ['tests/src']
60 |
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/Application/src/main/res/layout/sample_media_router_presentation.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
19 |
20 |
24 |
28 |
31 |
32 |
38 |
39 |
--------------------------------------------------------------------------------
/Application/tests/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
22 |
23 |
24 |
25 |
28 |
29 |
30 |
31 |
32 |
35 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/SampleMediaButtonReceiver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.content.BroadcastReceiver;
20 | import android.content.Context;
21 | import android.content.Intent;
22 | import android.view.KeyEvent;
23 |
24 | /**
25 | * Broadcast receiver for handling ACTION_MEDIA_BUTTON.
26 | *
27 | * This is needed to create the RemoteControlClient for controlling
28 | * remote route volume in lock screen. It routes media key events back
29 | * to main app activity MainActivity.
30 | */
31 | public class SampleMediaButtonReceiver extends BroadcastReceiver {
32 | private static final String TAG = "SampleMediaButtonReceiver";
33 | private static MainActivity mActivity;
34 |
35 | public static void setActivity(MainActivity activity) {
36 | mActivity = activity;
37 | }
38 |
39 | @Override
40 | public void onReceive(Context context, Intent intent) {
41 | if (mActivity != null && Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
42 | mActivity.handleMediaKey(
43 | (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT));
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/LogNode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
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.example.android.common.logger;
17 |
18 | /**
19 | * Basic interface for a logging system that can output to one or more targets.
20 | * Note that in addition to classes that will output these logs in some format,
21 | * one can also implement this interface over a filter and insert that in the chain,
22 | * such that no targets further down see certain data, or see manipulated forms of the data.
23 | * You could, for instance, write a "ToHtmlLoggerNode" that just converted all the log data
24 | * it received to HTML and sent it along to the next node in the chain, without printing it
25 | * anywhere.
26 | */
27 | public interface LogNode {
28 |
29 | /**
30 | * Instructs first LogNode in the list to print the log data provided.
31 | * @param priority Log level of the data being logged. Verbose, Error, etc.
32 | * @param tag Tag for for the log data. Can be used to organize log statements.
33 | * @param msg The actual message to be logged. The actual message to be logged.
34 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
35 | * to extract and print useful information.
36 | */
37 | public void println(int priority, String tag, String msg, Throwable tr);
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/MessageOnlyLogFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.common.logger;
17 |
18 | /**
19 | * Simple {@link LogNode} filter, removes everything except the message.
20 | * Useful for situations like on-screen log output where you don't want a lot of metadata displayed,
21 | * just easy-to-read message updates as they're happening.
22 | */
23 | public class MessageOnlyLogFilter implements LogNode {
24 |
25 | LogNode mNext;
26 |
27 | /**
28 | * Takes the "next" LogNode as a parameter, to simplify chaining.
29 | *
30 | * @param next The next LogNode in the pipeline.
31 | */
32 | public MessageOnlyLogFilter(LogNode next) {
33 | mNext = next;
34 | }
35 |
36 | public MessageOnlyLogFilter() {
37 | }
38 |
39 | @Override
40 | public void println(int priority, String tag, String msg, Throwable tr) {
41 | if (mNext != null) {
42 | getNext().println(Log.NONE, null, msg, null);
43 | }
44 | }
45 |
46 | /**
47 | * Returns the next LogNode in the chain.
48 | */
49 | public LogNode getNext() {
50 | return mNext;
51 | }
52 |
53 | /**
54 | * Sets the LogNode data will be sent to..
55 | */
56 | public void setNext(LogNode node) {
57 | mNext = node;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Application/tests/src/com/example/android/mediarouter/tests/SampleTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.tests;
17 |
18 | import com.example.android.mediarouter.player.MainActivity;
19 |
20 | import android.test.ActivityInstrumentationTestCase2;
21 |
22 | /**
23 | * Tests for MediaRouter sample.
24 | */
25 | public class SampleTests extends ActivityInstrumentationTestCase2 {
26 |
27 | private MainActivity mTestActivity;
28 |
29 | public SampleTests() {
30 | super(MainActivity.class);
31 | }
32 |
33 | @Override
34 | protected void setUp() throws Exception {
35 | super.setUp();
36 |
37 | // Starts the activity under test using the default Intent with:
38 | // action = {@link Intent#ACTION_MAIN}
39 | // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
40 | // All other fields are null or empty.
41 | mTestActivity = getActivity();
42 | }
43 |
44 | /**
45 | * Test if the test fixture has been set up correctly.
46 | */
47 | public void testPreconditions() {
48 | //Try to add a message to add context to your assertions. These messages will be shown if
49 | //a tests fails and make it easy to understand why a test failed
50 | assertNotNull("mTestActivity is null", mTestActivity);
51 | }
52 |
53 | /**
54 | * Add more tests below.
55 | */
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/Application/src/main/res/layout/media_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
19 |
20 |
27 |
28 |
36 |
37 |
45 |
46 |
--------------------------------------------------------------------------------
/Application/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
18 |
19 | This activity demonstrates how to
20 | use MediaRouter from the support library. Select a route from the action bar.
21 | Play on...
22 |
23 | Library
24 | Playlist
25 | Statistics
26 |
27 | Media Route Provider Service Support Library Sample
28 | Fixed Volume Remote Playback Route
29 | Variable Volume (Basic) Remote Playback Route
30 | Variable Volume (Queuing) Remote Playback Route
31 | Variable Volume (Session) Remote Playback Route
32 | Sample route
33 |
34 | Remote Playback (Simulated)
35 | Local Playback
36 | Local Playback on Presentation Display
37 | Added to playlist!
38 | Removed from playlist
39 |
40 |
41 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/LogWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
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.example.android.common.logger;
17 |
18 | import android.util.Log;
19 |
20 | /**
21 | * Helper class which wraps Android's native Log utility in the Logger interface. This way
22 | * normal DDMS output can be one of the many targets receiving and outputting logs simultaneously.
23 | */
24 | public class LogWrapper implements LogNode {
25 |
26 | // For piping: The next node to receive Log data after this one has done its work.
27 | private LogNode mNext;
28 |
29 | /**
30 | * Returns the next LogNode in the linked list.
31 | */
32 | public LogNode getNext() {
33 | return mNext;
34 | }
35 |
36 | /**
37 | * Sets the LogNode data will be sent to..
38 | */
39 | public void setNext(LogNode node) {
40 | mNext = node;
41 | }
42 |
43 | /**
44 | * Prints data out to the console using Android's native log mechanism.
45 | * @param priority Log level of the data being logged. Verbose, Error, etc.
46 | * @param tag Tag for for the log data. Can be used to organize log statements.
47 | * @param msg The actual message to be logged. The actual message to be logged.
48 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
49 | * to extract and print useful information.
50 | */
51 | @Override
52 | public void println(int priority, String tag, String msg, Throwable tr) {
53 | // There actually are log methods that don't take a msg parameter. For now,
54 | // if that's the case, just convert null to the empty string and move on.
55 | String useMsg = msg;
56 | if (useMsg == null) {
57 | useMsg = "";
58 | }
59 |
60 | // If an exeption was provided, convert that exception to a usable string and attach
61 | // it to the end of the msg method.
62 | if (tr != null) {
63 | msg += "\n" + Log.getStackTraceString(tr);
64 | }
65 |
66 | // This is functionally identical to Log.x(tag, useMsg);
67 | // For instance, if priority were Log.VERBOSE, this would be the same as Log.v(tag, useMsg)
68 | Log.println(priority, tag, useMsg);
69 |
70 | // If this isn't the last node in the chain, move things along.
71 | if (mNext != null) {
72 | mNext.println(priority, tag, msg, tr);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/Player.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.content.Context;
20 | import android.support.v7.media.MediaControlIntent;
21 | import android.support.v7.media.MediaRouter.RouteInfo;
22 |
23 | /**
24 | * Abstraction of common playback operations of media items, such as play,
25 | * seek, etc. Used by PlaybackManager as a backend to handle actual playback
26 | * of media items.
27 | */
28 | public abstract class Player {
29 | protected Callback mCallback;
30 |
31 | public abstract boolean isRemotePlayback();
32 | public abstract boolean isQueuingSupported();
33 |
34 | public abstract void connect(RouteInfo route);
35 | public abstract void release();
36 |
37 | // basic operations that are always supported
38 | public abstract void play(final PlaylistItem item);
39 | public abstract void seek(final PlaylistItem item);
40 | public abstract void getStatus(final PlaylistItem item, final boolean update);
41 | public abstract void pause();
42 | public abstract void resume();
43 | public abstract void stop();
44 |
45 | // advanced queuing (enqueue & remove) are only supported
46 | // if isQueuingSupported() returns true
47 | public abstract void enqueue(final PlaylistItem item);
48 | public abstract PlaylistItem remove(String iid);
49 |
50 | // route statistics
51 | public void updateStatistics() {}
52 | public String getStatistics() { return ""; }
53 |
54 | // presentation display
55 | public void updatePresentation() {}
56 |
57 | public void setCallback(Callback callback) {
58 | mCallback = callback;
59 | }
60 |
61 | public static Player create(Context context, RouteInfo route) {
62 | Player player;
63 | if (route != null && route.supportsControlCategory(
64 | MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)) {
65 | player = new RemotePlayer(context);
66 | } else if (route != null) {
67 | player = new LocalPlayer.SurfaceViewPlayer(context);
68 | } else {
69 | player = new LocalPlayer.OverlayPlayer(context);
70 | }
71 | player.connect(route);
72 | return player;
73 | }
74 |
75 | public interface Callback {
76 | void onError();
77 | void onCompletion();
78 | void onPlaylistChanged();
79 | void onPlaylistReady();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/Application/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
22 |
24 |
26 |
27 |
29 |
30 |
31 |
32 |
33 |
37 |
39 |
40 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/PlaylistItem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.app.PendingIntent;
20 | import android.net.Uri;
21 | import android.os.SystemClock;
22 | import android.support.v7.media.MediaItemStatus;
23 |
24 | /**
25 | * PlaylistItem helps keep track of the current status of an media item.
26 | */
27 | public final class PlaylistItem {
28 | // immutables
29 | private final String mSessionId;
30 | private final String mItemId;
31 | private final Uri mUri;
32 | private final String mMime;
33 | private final PendingIntent mUpdateReceiver;
34 | // changeable states
35 | private int mPlaybackState = MediaItemStatus.PLAYBACK_STATE_PENDING;
36 | private long mContentPosition;
37 | private long mContentDuration;
38 | private long mTimestamp;
39 | private String mRemoteItemId;
40 |
41 | public PlaylistItem(String qid, String iid, Uri uri, String mime, PendingIntent pi) {
42 | mSessionId = qid;
43 | mItemId = iid;
44 | mUri = uri;
45 | mMime = mime;
46 | mUpdateReceiver = pi;
47 | setTimestamp(SystemClock.elapsedRealtime());
48 | }
49 |
50 | public void setRemoteItemId(String riid) {
51 | mRemoteItemId = riid;
52 | }
53 |
54 | public void setState(int state) {
55 | mPlaybackState = state;
56 | }
57 |
58 | public void setPosition(long pos) {
59 | mContentPosition = pos;
60 | }
61 |
62 | public void setTimestamp(long ts) {
63 | mTimestamp = ts;
64 | }
65 |
66 | public void setDuration(long duration) {
67 | mContentDuration = duration;
68 | }
69 |
70 | public String getSessionId() {
71 | return mSessionId;
72 | }
73 |
74 | public String getItemId() {
75 | return mItemId;
76 | }
77 |
78 | public String getRemoteItemId() {
79 | return mRemoteItemId;
80 | }
81 |
82 | public Uri getUri() {
83 | return mUri;
84 | }
85 |
86 | public PendingIntent getUpdateReceiver() {
87 | return mUpdateReceiver;
88 | }
89 |
90 | public int getState() {
91 | return mPlaybackState;
92 | }
93 |
94 | public long getPosition() {
95 | return mContentPosition;
96 | }
97 |
98 | public long getDuration() {
99 | return mContentDuration;
100 | }
101 |
102 | public long getTimestamp() {
103 | return mTimestamp;
104 | }
105 |
106 | public MediaItemStatus getStatus() {
107 | return new MediaItemStatus.Builder(mPlaybackState)
108 | .setContentPosition(mContentPosition)
109 | .setContentDuration(mContentDuration)
110 | .setTimestamp(mTimestamp)
111 | .build();
112 | }
113 |
114 | @Override
115 | public String toString() {
116 | String state[] = {
117 | "PENDING",
118 | "PLAYING",
119 | "PAUSED",
120 | "BUFFERING",
121 | "FINISHED",
122 | "CANCELED",
123 | "INVALIDATED",
124 | "ERROR"
125 | };
126 | return "[" + mSessionId + "|" + mItemId + "|"
127 | + (mRemoteItemId != null ? mRemoteItemId : "-") + "|"
128 | + state[mPlaybackState] + "] " + mUri.toString();
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/LogFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 The Android Open Source Project
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 | * Copyright 2013 The Android Open Source Project
18 | *
19 | * Licensed under the Apache License, Version 2.0 (the "License");
20 | * you may not use this file except in compliance with the License.
21 | * You may obtain a copy of the License at
22 | *
23 | * http://www.apache.org/licenses/LICENSE-2.0
24 | *
25 | * Unless required by applicable law or agreed to in writing, software
26 | * distributed under the License is distributed on an "AS IS" BASIS,
27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28 | * See the License for the specific language governing permissions and
29 | * limitations under the License.
30 | */
31 |
32 | package com.example.android.common.logger;
33 |
34 | import android.graphics.Typeface;
35 | import android.os.Bundle;
36 | import android.support.v4.app.Fragment;
37 | import android.text.Editable;
38 | import android.text.TextWatcher;
39 | import android.view.Gravity;
40 | import android.view.LayoutInflater;
41 | import android.view.View;
42 | import android.view.ViewGroup;
43 | import android.widget.ScrollView;
44 |
45 | /**
46 | * Simple fraggment which contains a LogView and uses is to output log data it receives
47 | * through the LogNode interface.
48 | */
49 | public class LogFragment extends Fragment {
50 |
51 | private LogView mLogView;
52 | private ScrollView mScrollView;
53 |
54 | public LogFragment() {}
55 |
56 | public View inflateViews() {
57 | mScrollView = new ScrollView(getActivity());
58 | ViewGroup.LayoutParams scrollParams = new ViewGroup.LayoutParams(
59 | ViewGroup.LayoutParams.MATCH_PARENT,
60 | ViewGroup.LayoutParams.MATCH_PARENT);
61 | mScrollView.setLayoutParams(scrollParams);
62 |
63 | mLogView = new LogView(getActivity());
64 | ViewGroup.LayoutParams logParams = new ViewGroup.LayoutParams(scrollParams);
65 | logParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
66 | mLogView.setLayoutParams(logParams);
67 | mLogView.setClickable(true);
68 | mLogView.setFocusable(true);
69 | mLogView.setTypeface(Typeface.MONOSPACE);
70 |
71 | // Want to set padding as 16 dips, setPadding takes pixels. Hooray math!
72 | int paddingDips = 16;
73 | double scale = getResources().getDisplayMetrics().density;
74 | int paddingPixels = (int) ((paddingDips * (scale)) + .5);
75 | mLogView.setPadding(paddingPixels, paddingPixels, paddingPixels, paddingPixels);
76 | mLogView.setCompoundDrawablePadding(paddingPixels);
77 |
78 | mLogView.setGravity(Gravity.BOTTOM);
79 | mLogView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Holo_Medium);
80 |
81 | mScrollView.addView(mLogView);
82 | return mScrollView;
83 | }
84 |
85 | @Override
86 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
87 | Bundle savedInstanceState) {
88 |
89 | View result = inflateViews();
90 |
91 | mLogView.addTextChangedListener(new TextWatcher() {
92 | @Override
93 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
94 |
95 | @Override
96 | public void onTextChanged(CharSequence s, int start, int before, int count) {}
97 |
98 | @Override
99 | public void afterTextChanged(Editable s) {
100 | mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
101 | }
102 | });
103 | return result;
104 | }
105 |
106 | public LogView getLogView() {
107 | return mLogView;
108 | }
109 | }
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/LogView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.common.logger;
17 |
18 | import android.app.Activity;
19 | import android.content.Context;
20 | import android.util.*;
21 | import android.widget.TextView;
22 |
23 | /** Simple TextView which is used to output log data received through the LogNode interface.
24 | */
25 | public class LogView extends TextView implements LogNode {
26 |
27 | public LogView(Context context) {
28 | super(context);
29 | }
30 |
31 | public LogView(Context context, AttributeSet attrs) {
32 | super(context, attrs);
33 | }
34 |
35 | public LogView(Context context, AttributeSet attrs, int defStyle) {
36 | super(context, attrs, defStyle);
37 | }
38 |
39 | /**
40 | * Formats the log data and prints it out to the LogView.
41 | * @param priority Log level of the data being logged. Verbose, Error, etc.
42 | * @param tag Tag for for the log data. Can be used to organize log statements.
43 | * @param msg The actual message to be logged. The actual message to be logged.
44 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
45 | * to extract and print useful information.
46 | */
47 | @Override
48 | public void println(int priority, String tag, String msg, Throwable tr) {
49 |
50 |
51 | String priorityStr = null;
52 |
53 | // For the purposes of this View, we want to print the priority as readable text.
54 | switch(priority) {
55 | case android.util.Log.VERBOSE:
56 | priorityStr = "VERBOSE";
57 | break;
58 | case android.util.Log.DEBUG:
59 | priorityStr = "DEBUG";
60 | break;
61 | case android.util.Log.INFO:
62 | priorityStr = "INFO";
63 | break;
64 | case android.util.Log.WARN:
65 | priorityStr = "WARN";
66 | break;
67 | case android.util.Log.ERROR:
68 | priorityStr = "ERROR";
69 | break;
70 | case android.util.Log.ASSERT:
71 | priorityStr = "ASSERT";
72 | break;
73 | default:
74 | break;
75 | }
76 |
77 | // Handily, the Log class has a facility for converting a stack trace into a usable string.
78 | String exceptionStr = null;
79 | if (tr != null) {
80 | exceptionStr = android.util.Log.getStackTraceString(tr);
81 | }
82 |
83 | // Take the priority, tag, message, and exception, and concatenate as necessary
84 | // into one usable line of text.
85 | final StringBuilder outputBuilder = new StringBuilder();
86 |
87 | String delimiter = "\t";
88 | appendIfNotNull(outputBuilder, priorityStr, delimiter);
89 | appendIfNotNull(outputBuilder, tag, delimiter);
90 | appendIfNotNull(outputBuilder, msg, delimiter);
91 | appendIfNotNull(outputBuilder, exceptionStr, delimiter);
92 |
93 | // In case this was originally called from an AsyncTask or some other off-UI thread,
94 | // make sure the update occurs within the UI thread.
95 | ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() {
96 | @Override
97 | public void run() {
98 | // Display the text we just generated within the LogView.
99 | appendToLog(outputBuilder.toString());
100 | }
101 | })));
102 |
103 | if (mNext != null) {
104 | mNext.println(priority, tag, msg, tr);
105 | }
106 | }
107 |
108 | public LogNode getNext() {
109 | return mNext;
110 | }
111 |
112 | public void setNext(LogNode node) {
113 | mNext = node;
114 | }
115 |
116 | /** Takes a string and adds to it, with a separator, if the bit to be added isn't null. Since
117 | * the logger takes so many arguments that might be null, this method helps cut out some of the
118 | * agonizing tedium of writing the same 3 lines over and over.
119 | * @param source StringBuilder containing the text to append to.
120 | * @param addStr The String to append
121 | * @param delimiter The String to separate the source and appended strings. A tab or comma,
122 | * for instance.
123 | * @return The fully concatenated String as a StringBuilder
124 | */
125 | private StringBuilder appendIfNotNull(StringBuilder source, String addStr, String delimiter) {
126 | if (addStr != null) {
127 | if (addStr.length() == 0) {
128 | delimiter = "";
129 | }
130 |
131 | return source.append(addStr).append(delimiter);
132 | }
133 | return source;
134 | }
135 |
136 | // The next LogNode in the chain.
137 | LogNode mNext;
138 |
139 | /** Outputs the string as a new line of log data in the LogView. */
140 | public void appendToLog(String s) {
141 | append("\n" + s);
142 | }
143 |
144 |
145 | }
146 |
--------------------------------------------------------------------------------
/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/Application/src/main/res/layout/sample_media_router.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
18 |
19 |
23 |
28 |
29 |
33 |
37 |
40 |
41 |
44 |
48 |
53 |
54 |
55 |
59 |
63 |
64 |
65 |
69 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
84 |
85 |
93 |
94 |
103 |
104 |
113 |
114 |
115 |
116 |
117 |
118 |
123 |
127 |
130 |
131 |
137 |
138 |
139 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/common/logger/Log.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.common.logger;
17 |
18 | /**
19 | * Helper class for a list (or tree) of LoggerNodes.
20 | *
21 | * When this is set as the head of the list,
22 | * an instance of it can function as a drop-in replacement for {@link android.util.Log}.
23 | * Most of the methods in this class server only to map a method call in Log to its equivalent
24 | * in LogNode.
25 | */
26 | public class Log {
27 | // Grabbing the native values from Android's native logging facilities,
28 | // to make for easy migration and interop.
29 | public static final int NONE = -1;
30 | public static final int VERBOSE = android.util.Log.VERBOSE;
31 | public static final int DEBUG = android.util.Log.DEBUG;
32 | public static final int INFO = android.util.Log.INFO;
33 | public static final int WARN = android.util.Log.WARN;
34 | public static final int ERROR = android.util.Log.ERROR;
35 | public static final int ASSERT = android.util.Log.ASSERT;
36 |
37 | // Stores the beginning of the LogNode topology.
38 | private static LogNode mLogNode;
39 |
40 | /**
41 | * Returns the next LogNode in the linked list.
42 | */
43 | public static LogNode getLogNode() {
44 | return mLogNode;
45 | }
46 |
47 | /**
48 | * Sets the LogNode data will be sent to.
49 | */
50 | public static void setLogNode(LogNode node) {
51 | mLogNode = node;
52 | }
53 |
54 | /**
55 | * Instructs the LogNode to print the log data provided. Other LogNodes can
56 | * be chained to the end of the LogNode as desired.
57 | *
58 | * @param priority Log level of the data being logged. Verbose, Error, etc.
59 | * @param tag Tag for for the log data. Can be used to organize log statements.
60 | * @param msg The actual message to be logged.
61 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
62 | * to extract and print useful information.
63 | */
64 | public static void println(int priority, String tag, String msg, Throwable tr) {
65 | if (mLogNode != null) {
66 | mLogNode.println(priority, tag, msg, tr);
67 | }
68 | }
69 |
70 | /**
71 | * Instructs the LogNode to print the log data provided. Other LogNodes can
72 | * be chained to the end of the LogNode as desired.
73 | *
74 | * @param priority Log level of the data being logged. Verbose, Error, etc.
75 | * @param tag Tag for for the log data. Can be used to organize log statements.
76 | * @param msg The actual message to be logged. The actual message to be logged.
77 | */
78 | public static void println(int priority, String tag, String msg) {
79 | println(priority, tag, msg, null);
80 | }
81 |
82 | /**
83 | * Prints a message at VERBOSE priority.
84 | *
85 | * @param tag Tag for for the log data. Can be used to organize log statements.
86 | * @param msg The actual message to be logged.
87 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
88 | * to extract and print useful information.
89 | */
90 | public static void v(String tag, String msg, Throwable tr) {
91 | println(VERBOSE, tag, msg, tr);
92 | }
93 |
94 | /**
95 | * Prints a message at VERBOSE priority.
96 | *
97 | * @param tag Tag for for the log data. Can be used to organize log statements.
98 | * @param msg The actual message to be logged.
99 | */
100 | public static void v(String tag, String msg) {
101 | v(tag, msg, null);
102 | }
103 |
104 |
105 | /**
106 | * Prints a message at DEBUG priority.
107 | *
108 | * @param tag Tag for for the log data. Can be used to organize log statements.
109 | * @param msg The actual message to be logged.
110 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
111 | * to extract and print useful information.
112 | */
113 | public static void d(String tag, String msg, Throwable tr) {
114 | println(DEBUG, tag, msg, tr);
115 | }
116 |
117 | /**
118 | * Prints a message at DEBUG priority.
119 | *
120 | * @param tag Tag for for the log data. Can be used to organize log statements.
121 | * @param msg The actual message to be logged.
122 | */
123 | public static void d(String tag, String msg) {
124 | d(tag, msg, null);
125 | }
126 |
127 | /**
128 | * Prints a message at INFO priority.
129 | *
130 | * @param tag Tag for for the log data. Can be used to organize log statements.
131 | * @param msg The actual message to be logged.
132 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
133 | * to extract and print useful information.
134 | */
135 | public static void i(String tag, String msg, Throwable tr) {
136 | println(INFO, tag, msg, tr);
137 | }
138 |
139 | /**
140 | * Prints a message at INFO priority.
141 | *
142 | * @param tag Tag for for the log data. Can be used to organize log statements.
143 | * @param msg The actual message to be logged.
144 | */
145 | public static void i(String tag, String msg) {
146 | i(tag, msg, null);
147 | }
148 |
149 | /**
150 | * Prints a message at WARN priority.
151 | *
152 | * @param tag Tag for for the log data. Can be used to organize log statements.
153 | * @param msg The actual message to be logged.
154 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
155 | * to extract and print useful information.
156 | */
157 | public static void w(String tag, String msg, Throwable tr) {
158 | println(WARN, tag, msg, tr);
159 | }
160 |
161 | /**
162 | * Prints a message at WARN priority.
163 | *
164 | * @param tag Tag for for the log data. Can be used to organize log statements.
165 | * @param msg The actual message to be logged.
166 | */
167 | public static void w(String tag, String msg) {
168 | w(tag, msg, null);
169 | }
170 |
171 | /**
172 | * Prints a message at WARN priority.
173 | *
174 | * @param tag Tag for for the log data. Can be used to organize log statements.
175 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
176 | * to extract and print useful information.
177 | */
178 | public static void w(String tag, Throwable tr) {
179 | w(tag, null, tr);
180 | }
181 |
182 | /**
183 | * Prints a message at ERROR priority.
184 | *
185 | * @param tag Tag for for the log data. Can be used to organize log statements.
186 | * @param msg The actual message to be logged.
187 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
188 | * to extract and print useful information.
189 | */
190 | public static void e(String tag, String msg, Throwable tr) {
191 | println(ERROR, tag, msg, tr);
192 | }
193 |
194 | /**
195 | * Prints a message at ERROR priority.
196 | *
197 | * @param tag Tag for for the log data. Can be used to organize log statements.
198 | * @param msg The actual message to be logged.
199 | */
200 | public static void e(String tag, String msg) {
201 | e(tag, msg, null);
202 | }
203 |
204 | /**
205 | * Prints a message at ASSERT priority.
206 | *
207 | * @param tag Tag for for the log data. Can be used to organize log statements.
208 | * @param msg The actual message to be logged.
209 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
210 | * to extract and print useful information.
211 | */
212 | public static void wtf(String tag, String msg, Throwable tr) {
213 | println(ASSERT, tag, msg, tr);
214 | }
215 |
216 | /**
217 | * Prints a message at ASSERT priority.
218 | *
219 | * @param tag Tag for for the log data. Can be used to organize log statements.
220 | * @param msg The actual message to be logged.
221 | */
222 | public static void wtf(String tag, String msg) {
223 | wtf(tag, msg, null);
224 | }
225 |
226 | /**
227 | * Prints a message at ASSERT priority.
228 | *
229 | * @param tag Tag for for the log data. Can be used to organize log statements.
230 | * @param tr If an exception was thrown, this can be sent along for the logging facilities
231 | * to extract and print useful information.
232 | */
233 | public static void wtf(String tag, Throwable tr) {
234 | wtf(tag, null, tr);
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | --------------
3 |
4 | Version 2.0, January 2004
5 | http://www.apache.org/licenses/
6 |
7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 |
9 | 1. Definitions.
10 |
11 | "License" shall mean the terms and conditions for use, reproduction,
12 | and distribution as defined by Sections 1 through 9 of this document.
13 |
14 | "Licensor" shall mean the copyright owner or entity authorized by
15 | the copyright owner that is granting the License.
16 |
17 | "Legal Entity" shall mean the union of the acting entity and all
18 | other entities that control, are controlled by, or are under common
19 | control with that entity. For the purposes of this definition,
20 | "control" means (i) the power, direct or indirect, to cause the
21 | direction or management of such entity, whether by contract or
22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
23 | outstanding shares, or (iii) beneficial ownership of such entity.
24 |
25 | "You" (or "Your") shall mean an individual or Legal Entity
26 | exercising permissions granted by this License.
27 |
28 | "Source" form shall mean the preferred form for making modifications,
29 | including but not limited to software source code, documentation
30 | source, and configuration files.
31 |
32 | "Object" form shall mean any form resulting from mechanical
33 | transformation or translation of a Source form, including but
34 | not limited to compiled object code, generated documentation,
35 | and conversions to other media types.
36 |
37 | "Work" shall mean the work of authorship, whether in Source or
38 | Object form, made available under the License, as indicated by a
39 | copyright notice that is included in or attached to the work
40 | (an example is provided in the Appendix below).
41 |
42 | "Derivative Works" shall mean any work, whether in Source or Object
43 | form, that is based on (or derived from) the Work and for which the
44 | editorial revisions, annotations, elaborations, or other modifications
45 | represent, as a whole, an original work of authorship. For the purposes
46 | of this License, Derivative Works shall not include works that remain
47 | separable from, or merely link (or bind by name) to the interfaces of,
48 | the Work and Derivative Works thereof.
49 |
50 | "Contribution" shall mean any work of authorship, including
51 | the original version of the Work and any modifications or additions
52 | to that Work or Derivative Works thereof, that is intentionally
53 | submitted to Licensor for inclusion in the Work by the copyright owner
54 | or by an individual or Legal Entity authorized to submit on behalf of
55 | the copyright owner. For the purposes of this definition, "submitted"
56 | means any form of electronic, verbal, or written communication sent
57 | to the Licensor or its representatives, including but not limited to
58 | communication on electronic mailing lists, source code control systems,
59 | and issue tracking systems that are managed by, or on behalf of, the
60 | Licensor for the purpose of discussing and improving the Work, but
61 | excluding communication that is conspicuously marked or otherwise
62 | designated in writing by the copyright owner as "Not a Contribution."
63 |
64 | "Contributor" shall mean Licensor and any individual or Legal Entity
65 | on behalf of whom a Contribution has been received by Licensor and
66 | subsequently incorporated within the Work.
67 |
68 | 2. Grant of Copyright License. Subject to the terms and conditions of
69 | this License, each Contributor hereby grants to You a perpetual,
70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71 | copyright license to reproduce, prepare Derivative Works of,
72 | publicly display, publicly perform, sublicense, and distribute the
73 | Work and such Derivative Works in Source or Object form.
74 |
75 | 3. Grant of Patent License. Subject to the terms and conditions of
76 | this License, each Contributor hereby grants to You a perpetual,
77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78 | (except as stated in this section) patent license to make, have made,
79 | use, offer to sell, sell, import, and otherwise transfer the Work,
80 | where such license applies only to those patent claims licensable
81 | by such Contributor that are necessarily infringed by their
82 | Contribution(s) alone or by combination of their Contribution(s)
83 | with the Work to which such Contribution(s) was submitted. If You
84 | institute patent litigation against any entity (including a
85 | cross-claim or counterclaim in a lawsuit) alleging that the Work
86 | or a Contribution incorporated within the Work constitutes direct
87 | or contributory patent infringement, then any patent licenses
88 | granted to You under this License for that Work shall terminate
89 | as of the date such litigation is filed.
90 |
91 | 4. Redistribution. You may reproduce and distribute copies of the
92 | Work or Derivative Works thereof in any medium, with or without
93 | modifications, and in Source or Object form, provided that You
94 | meet the following conditions:
95 |
96 | (a) You must give any other recipients of the Work or
97 | Derivative Works a copy of this License; and
98 |
99 | (b) You must cause any modified files to carry prominent notices
100 | stating that You changed the files; and
101 |
102 | (c) You must retain, in the Source form of any Derivative Works
103 | that You distribute, all copyright, patent, trademark, and
104 | attribution notices from the Source form of the Work,
105 | excluding those notices that do not pertain to any part of
106 | the Derivative Works; and
107 |
108 | (d) If the Work includes a "NOTICE" text file as part of its
109 | distribution, then any Derivative Works that You distribute must
110 | include a readable copy of the attribution notices contained
111 | within such NOTICE file, excluding those notices that do not
112 | pertain to any part of the Derivative Works, in at least one
113 | of the following places: within a NOTICE text file distributed
114 | as part of the Derivative Works; within the Source form or
115 | documentation, if provided along with the Derivative Works; or,
116 | within a display generated by the Derivative Works, if and
117 | wherever such third-party notices normally appear. The contents
118 | of the NOTICE file are for informational purposes only and
119 | do not modify the License. You may add Your own attribution
120 | notices within Derivative Works that You distribute, alongside
121 | or as an addendum to the NOTICE text from the Work, provided
122 | that such additional attribution notices cannot be construed
123 | as modifying the License.
124 |
125 | You may add Your own copyright statement to Your modifications and
126 | may provide additional or different license terms and conditions
127 | for use, reproduction, or distribution of Your modifications, or
128 | for any such Derivative Works as a whole, provided Your use,
129 | reproduction, and distribution of the Work otherwise complies with
130 | the conditions stated in this License.
131 |
132 | 5. Submission of Contributions. Unless You explicitly state otherwise,
133 | any Contribution intentionally submitted for inclusion in the Work
134 | by You to the Licensor shall be under the terms and conditions of
135 | this License, without any additional terms or conditions.
136 | Notwithstanding the above, nothing herein shall supersede or modify
137 | the terms of any separate license agreement you may have executed
138 | with Licensor regarding such Contributions.
139 |
140 | 6. Trademarks. This License does not grant permission to use the trade
141 | names, trademarks, service marks, or product names of the Licensor,
142 | except as required for reasonable and customary use in describing the
143 | origin of the Work and reproducing the content of the NOTICE file.
144 |
145 | 7. Disclaimer of Warranty. Unless required by applicable law or
146 | agreed to in writing, Licensor provides the Work (and each
147 | Contributor provides its Contributions) on an "AS IS" BASIS,
148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149 | implied, including, without limitation, any warranties or conditions
150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151 | PARTICULAR PURPOSE. You are solely responsible for determining the
152 | appropriateness of using or redistributing the Work and assume any
153 | risks associated with Your exercise of permissions under this License.
154 |
155 | 8. Limitation of Liability. In no event and under no legal theory,
156 | whether in tort (including negligence), contract, or otherwise,
157 | unless required by applicable law (such as deliberate and grossly
158 | negligent acts) or agreed to in writing, shall any Contributor be
159 | liable to You for damages, including any direct, indirect, special,
160 | incidental, or consequential damages of any character arising as a
161 | result of this License or out of the use or inability to use the
162 | Work (including but not limited to damages for loss of goodwill,
163 | work stoppage, computer failure or malfunction, or any and all
164 | other commercial damages or losses), even if such Contributor
165 | has been advised of the possibility of such damages.
166 |
167 | 9. Accepting Warranty or Additional Liability. While redistributing
168 | the Work or Derivative Works thereof, You may choose to offer,
169 | and charge a fee for, acceptance of support, warranty, indemnity,
170 | or other liability obligations and/or rights consistent with this
171 | License. However, in accepting such obligations, You may act only
172 | on Your own behalf and on Your sole responsibility, not on behalf
173 | of any other Contributor, and only if You agree to indemnify,
174 | defend, and hold each Contributor harmless for any liability
175 | incurred by, or claims asserted against, such Contributor by reason
176 | of your accepting any such warranty or additional liability.
177 |
178 | END OF TERMS AND CONDITIONS
179 |
180 | APPENDIX: How to apply the Apache License to your work.
181 |
182 | To apply the Apache License to your work, attach the following
183 | boilerplate notice, with the fields enclosed by brackets "{}"
184 | replaced with your own identifying information. (Don't include
185 | the brackets!) The text should be enclosed in the appropriate
186 | comment syntax for the file format. We also recommend that a
187 | file or class name and description of purpose be included on the
188 | same "printed page" as the copyright notice for easier
189 | identification within third-party archives.
190 |
191 | Copyright {yyyy} {name of copyright owner}
192 |
193 | Licensed under the Apache License, Version 2.0 (the "License");
194 | you may not use this file except in compliance with the License.
195 | You may obtain a copy of the License at
196 |
197 | http://www.apache.org/licenses/LICENSE-2.0
198 |
199 | Unless required by applicable law or agreed to in writing, software
200 | distributed under the License is distributed on an "AS IS" BASIS,
201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 | See the License for the specific language governing permissions and
203 | limitations under the License.
204 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/SessionManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.app.PendingIntent;
20 | import android.net.Uri;
21 | import android.support.v7.media.MediaItemStatus;
22 | import android.support.v7.media.MediaSessionStatus;
23 | import android.util.Log;
24 |
25 | import com.example.android.mediarouter.player.Player.Callback;
26 |
27 | import java.util.ArrayList;
28 | import java.util.List;
29 |
30 | /**
31 | * SessionManager manages a media session as a queue. It supports common
32 | * queuing behaviors such as enqueue/remove of media items, pause/resume/stop,
33 | * etc.
34 | *
35 | * Actual playback of a single media item is abstracted into a Player interface,
36 | * and is handled outside this class.
37 | */
38 | public class SessionManager implements Callback {
39 | private static final String TAG = "SessionManager";
40 | private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
41 |
42 | private String mName;
43 | private int mSessionId;
44 | private int mItemId;
45 | private boolean mPaused;
46 | private boolean mSessionValid;
47 | private Player mPlayer;
48 | private Callback mCallback;
49 | private List mPlaylist = new ArrayList();
50 |
51 | public SessionManager(String name) {
52 | mName = name;
53 | }
54 |
55 | public boolean hasSession() {
56 | return mSessionValid;
57 | }
58 |
59 | public String getSessionId() {
60 | return mSessionValid ? Integer.toString(mSessionId) : null;
61 | }
62 |
63 | public PlaylistItem getCurrentItem() {
64 | return mPlaylist.isEmpty() ? null : mPlaylist.get(0);
65 | }
66 |
67 | // Get the cached statistic info from the player (will not update it)
68 | public String getStatistics() {
69 | checkPlayer();
70 | return mPlayer.getStatistics();
71 | }
72 |
73 | // Returns the cached playlist (note this is not responsible for updating it)
74 | public List getPlaylist() {
75 | return mPlaylist;
76 | }
77 |
78 | // Updates the playlist asynchronously, calls onPlaylistReady() when finished.
79 | public void updateStatus() {
80 | if (DEBUG) {
81 | log("updateStatus");
82 | }
83 | checkPlayer();
84 | // update the statistics first, so that the stats string is valid when
85 | // onPlaylistReady() gets called in the end
86 | mPlayer.updateStatistics();
87 |
88 | if (mPlaylist.isEmpty()) {
89 | // If queue is empty, don't forget to call onPlaylistReady()!
90 | onPlaylistReady();
91 | } else if (mPlayer.isQueuingSupported()) {
92 | // If player supports queuing, get status of each item. Player is
93 | // responsible to call onPlaylistReady() after last getStatus().
94 | // (update=1 requires player to callback onPlaylistReady())
95 | for (int i = 0; i < mPlaylist.size(); i++) {
96 | PlaylistItem item = mPlaylist.get(i);
97 | mPlayer.getStatus(item, (i == mPlaylist.size() - 1) /* update */);
98 | }
99 | } else {
100 | // Otherwise, only need to get status for current item. Player is
101 | // responsible to call onPlaylistReady() when finished.
102 | mPlayer.getStatus(getCurrentItem(), true /* update */);
103 | }
104 | }
105 |
106 | public PlaylistItem add(Uri uri, String mime) {
107 | return add(uri, mime, null);
108 | }
109 |
110 | public PlaylistItem add(Uri uri, String mime, PendingIntent receiver) {
111 | if (DEBUG) {
112 | log("add: uri=" + uri + ", receiver=" + receiver);
113 | }
114 | // create new session if needed
115 | startSession();
116 | checkPlayerAndSession();
117 |
118 | // append new item with initial status PLAYBACK_STATE_PENDING
119 | PlaylistItem item = new PlaylistItem(
120 | Integer.toString(mSessionId), Integer.toString(mItemId), uri, mime, receiver);
121 | mPlaylist.add(item);
122 | mItemId++;
123 |
124 | // if player supports queuing, enqueue the item now
125 | if (mPlayer.isQueuingSupported()) {
126 | mPlayer.enqueue(item);
127 | }
128 | updatePlaybackState();
129 | return item;
130 | }
131 |
132 | public PlaylistItem remove(String iid) {
133 | if (DEBUG) {
134 | log("remove: iid=" + iid);
135 | }
136 | checkPlayerAndSession();
137 | return removeItem(iid, MediaItemStatus.PLAYBACK_STATE_CANCELED);
138 | }
139 |
140 | public PlaylistItem seek(String iid, long pos) {
141 | if (DEBUG) {
142 | log("seek: iid=" + iid +", pos=" + pos);
143 | }
144 | checkPlayerAndSession();
145 | // seeking on pending items are not yet supported
146 | checkItemCurrent(iid);
147 |
148 | PlaylistItem item = getCurrentItem();
149 | if (pos != item.getPosition()) {
150 | item.setPosition(pos);
151 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
152 | || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
153 | mPlayer.seek(item);
154 | }
155 | }
156 | return item;
157 | }
158 |
159 | public PlaylistItem getStatus(String iid) {
160 | checkPlayerAndSession();
161 |
162 | // This should only be called for local player. Remote player is
163 | // asynchronous, need to use updateStatus() instead.
164 | if (mPlayer.isRemotePlayback()) {
165 | throw new IllegalStateException(
166 | "getStatus should not be called on remote player!");
167 | }
168 |
169 | for (PlaylistItem item : mPlaylist) {
170 | if (item.getItemId().equals(iid)) {
171 | if (item == getCurrentItem()) {
172 | mPlayer.getStatus(item, false);
173 | }
174 | return item;
175 | }
176 | }
177 | return null;
178 | }
179 |
180 | public void pause() {
181 | if (DEBUG) {
182 | log("pause");
183 | }
184 | mPaused = true;
185 | updatePlaybackState();
186 | }
187 |
188 | public void resume() {
189 | if (DEBUG) {
190 | log("resume");
191 | }
192 | mPaused = false;
193 | updatePlaybackState();
194 | }
195 |
196 | public void stop() {
197 | if (DEBUG) {
198 | log("stop");
199 | }
200 | mPlayer.stop();
201 | mPlaylist.clear();
202 | mPaused = false;
203 | updateStatus();
204 | }
205 |
206 | public String startSession() {
207 | if (!mSessionValid) {
208 | mSessionId++;
209 | mItemId = 0;
210 | mPaused = false;
211 | mSessionValid = true;
212 | return Integer.toString(mSessionId);
213 | }
214 | return null;
215 | }
216 |
217 | public boolean endSession() {
218 | if (mSessionValid) {
219 | mSessionValid = false;
220 | return true;
221 | }
222 | return false;
223 | }
224 |
225 | public MediaSessionStatus getSessionStatus(String sid) {
226 | int sessionState = (sid != null && sid.equals(mSessionId)) ?
227 | MediaSessionStatus.SESSION_STATE_ACTIVE :
228 | MediaSessionStatus.SESSION_STATE_INVALIDATED;
229 |
230 | return new MediaSessionStatus.Builder(sessionState)
231 | .setQueuePaused(mPaused)
232 | .build();
233 | }
234 |
235 | // Suspend the playback manager. Put the current item back into PENDING
236 | // state, and remember the current playback position. Called when switching
237 | // to a different player (route).
238 | public void suspend(long pos) {
239 | for (PlaylistItem item : mPlaylist) {
240 | item.setRemoteItemId(null);
241 | item.setDuration(0);
242 | }
243 | PlaylistItem item = getCurrentItem();
244 | if (DEBUG) {
245 | log("suspend: item=" + item + ", pos=" + pos);
246 | }
247 | if (item != null) {
248 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
249 | || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
250 | item.setState(MediaItemStatus.PLAYBACK_STATE_PENDING);
251 | item.setPosition(pos);
252 | }
253 | }
254 | }
255 |
256 | // Unsuspend the playback manager. Restart playback on new player (route).
257 | // This will resume playback of current item. Furthermore, if the new player
258 | // supports queuing, playlist will be re-established on the remote player.
259 | public void unsuspend() {
260 | if (DEBUG) {
261 | log("unsuspend");
262 | }
263 | if (mPlayer.isQueuingSupported()) {
264 | for (PlaylistItem item : mPlaylist) {
265 | mPlayer.enqueue(item);
266 | }
267 | }
268 | updatePlaybackState();
269 | }
270 |
271 | // Player.Callback
272 | @Override
273 | public void onError() {
274 | finishItem(true);
275 | }
276 |
277 | @Override
278 | public void onCompletion() {
279 | finishItem(false);
280 | }
281 |
282 | @Override
283 | public void onPlaylistChanged() {
284 | // Playlist has changed, update the cached playlist
285 | updateStatus();
286 | }
287 |
288 | @Override
289 | public void onPlaylistReady() {
290 | // Notify activity to update Ui
291 | if (mCallback != null) {
292 | mCallback.onStatusChanged();
293 | }
294 | }
295 |
296 | private void log(String message) {
297 | Log.d(TAG, mName + ": " + message);
298 | }
299 |
300 | private void checkPlayer() {
301 | if (mPlayer == null) {
302 | throw new IllegalStateException("Player not set!");
303 | }
304 | }
305 |
306 | private void checkSession() {
307 | if (!mSessionValid) {
308 | throw new IllegalStateException("Session not set!");
309 | }
310 | }
311 |
312 | private void checkPlayerAndSession() {
313 | checkPlayer();
314 | checkSession();
315 | }
316 |
317 | private void checkItemCurrent(String iid) {
318 | PlaylistItem item = getCurrentItem();
319 | if (item == null || !item.getItemId().equals(iid)) {
320 | throw new IllegalArgumentException("Item is not current!");
321 | }
322 | }
323 |
324 | private void updatePlaybackState() {
325 | PlaylistItem item = getCurrentItem();
326 | if (item != null) {
327 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PENDING) {
328 | item.setState(mPaused ? MediaItemStatus.PLAYBACK_STATE_PAUSED
329 | : MediaItemStatus.PLAYBACK_STATE_PLAYING);
330 | if (!mPlayer.isQueuingSupported()) {
331 | mPlayer.play(item);
332 | }
333 | } else if (mPaused && item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING) {
334 | mPlayer.pause();
335 | item.setState(MediaItemStatus.PLAYBACK_STATE_PAUSED);
336 | } else if (!mPaused && item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
337 | mPlayer.resume();
338 | item.setState(MediaItemStatus.PLAYBACK_STATE_PLAYING);
339 | }
340 | // notify client that item playback status has changed
341 | if (mCallback != null) {
342 | mCallback.onItemChanged(item);
343 | }
344 | }
345 | updateStatus();
346 | }
347 |
348 | private PlaylistItem removeItem(String iid, int state) {
349 | checkPlayerAndSession();
350 | List queue =
351 | new ArrayList(mPlaylist.size());
352 | PlaylistItem found = null;
353 | for (PlaylistItem item : mPlaylist) {
354 | if (iid.equals(item.getItemId())) {
355 | if (mPlayer.isQueuingSupported()) {
356 | mPlayer.remove(item.getRemoteItemId());
357 | } else if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING
358 | || item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED){
359 | mPlayer.stop();
360 | }
361 | item.setState(state);
362 | found = item;
363 | // notify client that item is now removed
364 | if (mCallback != null) {
365 | mCallback.onItemChanged(found);
366 | }
367 | } else {
368 | queue.add(item);
369 | }
370 | }
371 | if (found != null) {
372 | mPlaylist = queue;
373 | updatePlaybackState();
374 | } else {
375 | log("item not found");
376 | }
377 | return found;
378 | }
379 |
380 | private void finishItem(boolean error) {
381 | PlaylistItem item = getCurrentItem();
382 | if (item != null) {
383 | removeItem(item.getItemId(), error ?
384 | MediaItemStatus.PLAYBACK_STATE_ERROR :
385 | MediaItemStatus.PLAYBACK_STATE_FINISHED);
386 | updateStatus();
387 | }
388 | }
389 |
390 | // set the Player that this playback manager will interact with
391 | public void setPlayer(Player player) {
392 | mPlayer = player;
393 | checkPlayer();
394 | mPlayer.setCallback(this);
395 | }
396 |
397 | // provide a callback interface to tell the UI when significant state changes occur
398 | public void setCallback(Callback callback) {
399 | mCallback = callback;
400 | }
401 |
402 | @Override
403 | public String toString() {
404 | String result = "Media Queue: ";
405 | if (!mPlaylist.isEmpty()) {
406 | for (PlaylistItem item : mPlaylist) {
407 | result += "\n" + item.toString();
408 | }
409 | } else {
410 | result += "";
411 | }
412 | return result;
413 | }
414 |
415 | public interface Callback {
416 | void onStatusChanged();
417 | void onItemChanged(PlaylistItem item);
418 | }
419 | }
420 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/RemotePlayer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.content.Context;
20 | import android.content.Intent;
21 | import android.os.Bundle;
22 | import android.support.v7.media.MediaItemStatus;
23 | import android.support.v7.media.MediaRouter.ControlRequestCallback;
24 | import android.support.v7.media.MediaRouter.RouteInfo;
25 | import android.support.v7.media.MediaSessionStatus;
26 | import android.support.v7.media.RemotePlaybackClient;
27 | import android.support.v7.media.RemotePlaybackClient.ItemActionCallback;
28 | import android.support.v7.media.RemotePlaybackClient.SessionActionCallback;
29 | import android.support.v7.media.RemotePlaybackClient.StatusCallback;
30 | import android.util.Log;
31 |
32 | import com.example.android.mediarouter.player.Player;
33 | import com.example.android.mediarouter.player.PlaylistItem;
34 | import com.example.android.mediarouter.provider.SampleMediaRouteProvider;
35 |
36 | import java.util.ArrayList;
37 | import java.util.List;
38 |
39 | /**
40 | * Handles playback of media items using a remote route.
41 | *
42 | * This class is used as a backend by PlaybackManager to feed media items to
43 | * the remote route. When the remote route doesn't support queuing, media items
44 | * are fed one-at-a-time; otherwise media items are enqueued to the remote side.
45 | */
46 | public class RemotePlayer extends Player {
47 | private static final String TAG = "RemotePlayer";
48 | private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
49 | private Context mContext;
50 | private RouteInfo mRoute;
51 | private boolean mEnqueuePending;
52 | private String mStatsInfo = "";
53 | private List mTempQueue = new ArrayList();
54 |
55 | private RemotePlaybackClient mClient;
56 | private StatusCallback mStatusCallback = new StatusCallback() {
57 | @Override
58 | public void onItemStatusChanged(Bundle data,
59 | String sessionId, MediaSessionStatus sessionStatus,
60 | String itemId, MediaItemStatus itemStatus) {
61 | logStatus("onItemStatusChanged", sessionId, sessionStatus, itemId, itemStatus);
62 | if (mCallback != null) {
63 | if (itemStatus.getPlaybackState() ==
64 | MediaItemStatus.PLAYBACK_STATE_FINISHED) {
65 | mCallback.onCompletion();
66 | } else if (itemStatus.getPlaybackState() ==
67 | MediaItemStatus.PLAYBACK_STATE_ERROR) {
68 | mCallback.onError();
69 | }
70 | }
71 | }
72 |
73 | @Override
74 | public void onSessionStatusChanged(Bundle data,
75 | String sessionId, MediaSessionStatus sessionStatus) {
76 | logStatus("onSessionStatusChanged", sessionId, sessionStatus, null, null);
77 | if (mCallback != null) {
78 | mCallback.onPlaylistChanged();
79 | }
80 | }
81 |
82 | @Override
83 | public void onSessionChanged(String sessionId) {
84 | if (DEBUG) {
85 | Log.d(TAG, "onSessionChanged: sessionId=" + sessionId);
86 | }
87 | }
88 | };
89 |
90 | public RemotePlayer(Context context) {
91 | mContext = context;
92 | }
93 |
94 | @Override
95 | public boolean isRemotePlayback() {
96 | return true;
97 | }
98 |
99 | @Override
100 | public boolean isQueuingSupported() {
101 | return mClient.isQueuingSupported();
102 | }
103 |
104 | @Override
105 | public void connect(RouteInfo route) {
106 | mRoute = route;
107 | mClient = new RemotePlaybackClient(mContext, route);
108 | mClient.setStatusCallback(mStatusCallback);
109 |
110 | if (DEBUG) {
111 | Log.d(TAG, "connected to: " + route
112 | + ", isRemotePlaybackSupported: " + mClient.isRemotePlaybackSupported()
113 | + ", isQueuingSupported: "+ mClient.isQueuingSupported());
114 | }
115 | }
116 |
117 | @Override
118 | public void release() {
119 | mClient.release();
120 |
121 | if (DEBUG) {
122 | Log.d(TAG, "released.");
123 | }
124 | }
125 |
126 | // basic playback operations that are always supported
127 | @Override
128 | public void play(final PlaylistItem item) {
129 | if (DEBUG) {
130 | Log.d(TAG, "play: item=" + item);
131 | }
132 | mClient.play(item.getUri(), "video/mp4", null, 0, null, new ItemActionCallback() {
133 | @Override
134 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus,
135 | String itemId, MediaItemStatus itemStatus) {
136 | logStatus("play: succeeded", sessionId, sessionStatus, itemId, itemStatus);
137 | item.setRemoteItemId(itemId);
138 | if (item.getPosition() > 0) {
139 | seekInternal(item);
140 | }
141 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
142 | pause();
143 | }
144 | if (mCallback != null) {
145 | mCallback.onPlaylistChanged();
146 | }
147 | }
148 |
149 | @Override
150 | public void onError(String error, int code, Bundle data) {
151 | logError("play: failed", error, code);
152 | }
153 | });
154 | }
155 |
156 | @Override
157 | public void seek(final PlaylistItem item) {
158 | seekInternal(item);
159 | }
160 |
161 | @Override
162 | public void getStatus(final PlaylistItem item, final boolean update) {
163 | if (!mClient.hasSession() || item.getRemoteItemId() == null) {
164 | // if session is not valid or item id not assigend yet.
165 | // just return, it's not fatal
166 | return;
167 | }
168 |
169 | if (DEBUG) {
170 | Log.d(TAG, "getStatus: item=" + item + ", update=" + update);
171 | }
172 | mClient.getStatus(item.getRemoteItemId(), null, new ItemActionCallback() {
173 | @Override
174 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus,
175 | String itemId, MediaItemStatus itemStatus) {
176 | logStatus("getStatus: succeeded", sessionId, sessionStatus, itemId, itemStatus);
177 | int state = itemStatus.getPlaybackState();
178 | if (state == MediaItemStatus.PLAYBACK_STATE_PLAYING
179 | || state == MediaItemStatus.PLAYBACK_STATE_PAUSED
180 | || state == MediaItemStatus.PLAYBACK_STATE_PENDING) {
181 | item.setState(state);
182 | item.setPosition(itemStatus.getContentPosition());
183 | item.setDuration(itemStatus.getContentDuration());
184 | item.setTimestamp(itemStatus.getTimestamp());
185 | }
186 | if (update && mCallback != null) {
187 | mCallback.onPlaylistReady();
188 | }
189 | }
190 |
191 | @Override
192 | public void onError(String error, int code, Bundle data) {
193 | logError("getStatus: failed", error, code);
194 | if (update && mCallback != null) {
195 | mCallback.onPlaylistReady();
196 | }
197 | }
198 | });
199 | }
200 |
201 | @Override
202 | public void pause() {
203 | if (!mClient.hasSession()) {
204 | // ignore if no session
205 | return;
206 | }
207 | if (DEBUG) {
208 | Log.d(TAG, "pause");
209 | }
210 | mClient.pause(null, new SessionActionCallback() {
211 | @Override
212 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus) {
213 | logStatus("pause: succeeded", sessionId, sessionStatus, null, null);
214 | if (mCallback != null) {
215 | mCallback.onPlaylistChanged();
216 | }
217 | }
218 |
219 | @Override
220 | public void onError(String error, int code, Bundle data) {
221 | logError("pause: failed", error, code);
222 | }
223 | });
224 | }
225 |
226 | @Override
227 | public void resume() {
228 | if (!mClient.hasSession()) {
229 | // ignore if no session
230 | return;
231 | }
232 | if (DEBUG) {
233 | Log.d(TAG, "resume");
234 | }
235 | mClient.resume(null, new SessionActionCallback() {
236 | @Override
237 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus) {
238 | logStatus("resume: succeeded", sessionId, sessionStatus, null, null);
239 | if (mCallback != null) {
240 | mCallback.onPlaylistChanged();
241 | }
242 | }
243 |
244 | @Override
245 | public void onError(String error, int code, Bundle data) {
246 | logError("resume: failed", error, code);
247 | }
248 | });
249 | }
250 |
251 | @Override
252 | public void stop() {
253 | if (!mClient.hasSession()) {
254 | // ignore if no session
255 | return;
256 | }
257 | if (DEBUG) {
258 | Log.d(TAG, "stop");
259 | }
260 | mClient.stop(null, new SessionActionCallback() {
261 | @Override
262 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus) {
263 | logStatus("stop: succeeded", sessionId, sessionStatus, null, null);
264 | if (mClient.isSessionManagementSupported()) {
265 | endSession();
266 | }
267 | if (mCallback != null) {
268 | mCallback.onPlaylistChanged();
269 | }
270 | }
271 |
272 | @Override
273 | public void onError(String error, int code, Bundle data) {
274 | logError("stop: failed", error, code);
275 | }
276 | });
277 | }
278 |
279 | // enqueue & remove are only supported if isQueuingSupported() returns true
280 | @Override
281 | public void enqueue(final PlaylistItem item) {
282 | throwIfQueuingUnsupported();
283 |
284 | if (!mClient.hasSession() && !mEnqueuePending) {
285 | mEnqueuePending = true;
286 | if (mClient.isSessionManagementSupported()) {
287 | startSession(item);
288 | } else {
289 | enqueueInternal(item);
290 | }
291 | } else if (mEnqueuePending){
292 | mTempQueue.add(item);
293 | } else {
294 | enqueueInternal(item);
295 | }
296 | }
297 |
298 | @Override
299 | public PlaylistItem remove(String itemId) {
300 | throwIfNoSession();
301 | throwIfQueuingUnsupported();
302 |
303 | if (DEBUG) {
304 | Log.d(TAG, "remove: itemId=" + itemId);
305 | }
306 | mClient.remove(itemId, null, new ItemActionCallback() {
307 | @Override
308 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus,
309 | String itemId, MediaItemStatus itemStatus) {
310 | logStatus("remove: succeeded", sessionId, sessionStatus, itemId, itemStatus);
311 | }
312 |
313 | @Override
314 | public void onError(String error, int code, Bundle data) {
315 | logError("remove: failed", error, code);
316 | }
317 | });
318 |
319 | return null;
320 | }
321 |
322 | @Override
323 | public void updateStatistics() {
324 | // clear stats info first
325 | mStatsInfo = "";
326 |
327 | Intent intent = new Intent(SampleMediaRouteProvider.ACTION_GET_STATISTICS);
328 | intent.addCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE);
329 |
330 | if (mRoute != null && mRoute.supportsControlRequest(intent)) {
331 | ControlRequestCallback callback = new ControlRequestCallback() {
332 | @Override
333 | public void onResult(Bundle data) {
334 | if (DEBUG) {
335 | Log.d(TAG, "getStatistics: succeeded: data=" + data);
336 | }
337 | if (data != null) {
338 | int playbackCount = data.getInt(
339 | SampleMediaRouteProvider.DATA_PLAYBACK_COUNT, -1);
340 | mStatsInfo = "Total playback count: " + playbackCount;
341 | }
342 | }
343 |
344 | @Override
345 | public void onError(String error, Bundle data) {
346 | Log.d(TAG, "getStatistics: failed: error=" + error + ", data=" + data);
347 | }
348 | };
349 |
350 | mRoute.sendControlRequest(intent, callback);
351 | }
352 | }
353 |
354 | @Override
355 | public String getStatistics() {
356 | return mStatsInfo;
357 | }
358 |
359 | private void enqueueInternal(final PlaylistItem item) {
360 | throwIfQueuingUnsupported();
361 |
362 | if (DEBUG) {
363 | Log.d(TAG, "enqueue: item=" + item);
364 | }
365 | mClient.enqueue(item.getUri(), "video/mp4", null, 0, null, new ItemActionCallback() {
366 | @Override
367 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus,
368 | String itemId, MediaItemStatus itemStatus) {
369 | logStatus("enqueue: succeeded", sessionId, sessionStatus, itemId, itemStatus);
370 | item.setRemoteItemId(itemId);
371 | if (item.getPosition() > 0) {
372 | seekInternal(item);
373 | }
374 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
375 | pause();
376 | }
377 | if (mEnqueuePending) {
378 | mEnqueuePending = false;
379 | for (PlaylistItem item : mTempQueue) {
380 | enqueueInternal(item);
381 | }
382 | mTempQueue.clear();
383 | }
384 | if (mCallback != null) {
385 | mCallback.onPlaylistChanged();
386 | }
387 | }
388 |
389 | @Override
390 | public void onError(String error, int code, Bundle data) {
391 | logError("enqueue: failed", error, code);
392 | if (mCallback != null) {
393 | mCallback.onPlaylistChanged();
394 | }
395 | }
396 | });
397 | }
398 |
399 | private void seekInternal(final PlaylistItem item) {
400 | throwIfNoSession();
401 |
402 | if (DEBUG) {
403 | Log.d(TAG, "seek: item=" + item);
404 | }
405 | mClient.seek(item.getRemoteItemId(), item.getPosition(), null, new ItemActionCallback() {
406 | @Override
407 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus,
408 | String itemId, MediaItemStatus itemStatus) {
409 | logStatus("seek: succeeded", sessionId, sessionStatus, itemId, itemStatus);
410 | if (mCallback != null) {
411 | mCallback.onPlaylistChanged();
412 | }
413 | }
414 |
415 | @Override
416 | public void onError(String error, int code, Bundle data) {
417 | logError("seek: failed", error, code);
418 | }
419 | });
420 | }
421 |
422 | private void startSession(final PlaylistItem item) {
423 | mClient.startSession(null, new SessionActionCallback() {
424 | @Override
425 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus) {
426 | logStatus("startSession: succeeded", sessionId, sessionStatus, null, null);
427 | enqueueInternal(item);
428 | }
429 |
430 | @Override
431 | public void onError(String error, int code, Bundle data) {
432 | logError("startSession: failed", error, code);
433 | }
434 | });
435 | }
436 |
437 | private void endSession() {
438 | mClient.endSession(null, new SessionActionCallback() {
439 | @Override
440 | public void onResult(Bundle data, String sessionId, MediaSessionStatus sessionStatus) {
441 | logStatus("endSession: succeeded", sessionId, sessionStatus, null, null);
442 | }
443 |
444 | @Override
445 | public void onError(String error, int code, Bundle data) {
446 | logError("endSession: failed", error, code);
447 | }
448 | });
449 | }
450 |
451 | private void logStatus(String message,
452 | String sessionId, MediaSessionStatus sessionStatus,
453 | String itemId, MediaItemStatus itemStatus) {
454 | if (DEBUG) {
455 | String result = "";
456 | if (sessionId != null && sessionStatus != null) {
457 | result += "sessionId=" + sessionId + ", sessionStatus=" + sessionStatus;
458 | }
459 | if (itemId != null & itemStatus != null) {
460 | result += (result.isEmpty() ? "" : ", ")
461 | + "itemId=" + itemId + ", itemStatus=" + itemStatus;
462 | }
463 | Log.d(TAG, message + ": " + result);
464 | }
465 | }
466 |
467 | private void logError(String message, String error, int code) {
468 | Log.d(TAG, message + ": error=" + error + ", code=" + code);
469 | }
470 |
471 | private void throwIfNoSession() {
472 | if (!mClient.hasSession()) {
473 | throw new IllegalStateException("Session is invalid");
474 | }
475 | }
476 |
477 | private void throwIfQueuingUnsupported() {
478 | if (!isQueuingSupported()) {
479 | throw new UnsupportedOperationException("Queuing is unsupported");
480 | }
481 | }
482 | }
483 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/OverlayDisplayWindow.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.content.Context;
20 | import android.graphics.SurfaceTexture;
21 | import android.hardware.display.DisplayManager;
22 | import android.os.Build;
23 | import android.util.DisplayMetrics;
24 | import android.util.Log;
25 | import android.view.Display;
26 | import android.view.GestureDetector;
27 | import android.view.Gravity;
28 | import android.view.LayoutInflater;
29 | import android.view.MotionEvent;
30 | import android.view.ScaleGestureDetector;
31 | import android.view.Surface;
32 | import android.view.SurfaceHolder;
33 | import android.view.SurfaceView;
34 | import android.view.TextureView;
35 | import android.view.TextureView.SurfaceTextureListener;
36 | import android.view.View;
37 | import android.view.WindowManager;
38 | import android.widget.TextView;
39 |
40 | import com.example.android.mediarouter.R;
41 |
42 | /**
43 | * Manages an overlay display window, used for simulating remote playback.
44 | */
45 | public abstract class OverlayDisplayWindow {
46 | private static final String TAG = "OverlayDisplayWindow";
47 | private static final boolean DEBUG = false;
48 |
49 | private static final float WINDOW_ALPHA = 0.8f;
50 | private static final float INITIAL_SCALE = 0.5f;
51 | private static final float MIN_SCALE = 0.3f;
52 | private static final float MAX_SCALE = 1.0f;
53 |
54 | protected final Context mContext;
55 | protected final String mName;
56 | protected final int mWidth;
57 | protected final int mHeight;
58 | protected final int mGravity;
59 | protected OverlayWindowListener mListener;
60 |
61 | protected OverlayDisplayWindow(Context context, String name,
62 | int width, int height, int gravity) {
63 | mContext = context;
64 | mName = name;
65 | mWidth = width;
66 | mHeight = height;
67 | mGravity = gravity;
68 | }
69 |
70 | public static OverlayDisplayWindow create(Context context, String name,
71 | int width, int height, int gravity) {
72 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
73 | return new JellybeanMr1Impl(context, name, width, height, gravity);
74 | } else {
75 | return new LegacyImpl(context, name, width, height, gravity);
76 | }
77 | }
78 |
79 | public void setOverlayWindowListener(OverlayWindowListener listener) {
80 | mListener = listener;
81 | }
82 |
83 | public Context getContext() {
84 | return mContext;
85 | }
86 |
87 | public abstract void show();
88 |
89 | public abstract void dismiss();
90 |
91 | public abstract void updateAspectRatio(int width, int height);
92 |
93 | // Watches for significant changes in the overlay display window lifecycle.
94 | public interface OverlayWindowListener {
95 | public void onWindowCreated(Surface surface);
96 | public void onWindowCreated(SurfaceHolder surfaceHolder);
97 | public void onWindowDestroyed();
98 | }
99 |
100 | /**
101 | * Implementation for older versions.
102 | */
103 | private static final class LegacyImpl extends OverlayDisplayWindow {
104 | private final WindowManager mWindowManager;
105 |
106 | private boolean mWindowVisible;
107 | private SurfaceView mSurfaceView;
108 |
109 | public LegacyImpl(Context context, String name,
110 | int width, int height, int gravity) {
111 | super(context, name, width, height, gravity);
112 |
113 | mWindowManager = (WindowManager)context.getSystemService(
114 | Context.WINDOW_SERVICE);
115 | }
116 |
117 | @Override
118 | public void show() {
119 | if (!mWindowVisible) {
120 | mSurfaceView = new SurfaceView(mContext);
121 |
122 | Display display = mWindowManager.getDefaultDisplay();
123 |
124 | WindowManager.LayoutParams params = new WindowManager.LayoutParams(
125 | WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
126 | params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
127 | | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
128 | | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
129 | | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
130 | | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
131 | params.alpha = WINDOW_ALPHA;
132 | params.gravity = Gravity.LEFT | Gravity.BOTTOM;
133 | params.setTitle(mName);
134 |
135 | int width = (int)(display.getWidth() * INITIAL_SCALE);
136 | int height = (int)(display.getHeight() * INITIAL_SCALE);
137 | if (mWidth > mHeight) {
138 | height = mHeight * width / mWidth;
139 | } else {
140 | width = mWidth * height / mHeight;
141 | }
142 | params.width = width;
143 | params.height = height;
144 |
145 | mWindowManager.addView(mSurfaceView, params);
146 | mWindowVisible = true;
147 |
148 | SurfaceHolder holder = mSurfaceView.getHolder();
149 | holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
150 | mListener.onWindowCreated(holder);
151 | }
152 | }
153 |
154 | @Override
155 | public void dismiss() {
156 | if (mWindowVisible) {
157 | mListener.onWindowDestroyed();
158 |
159 | mWindowManager.removeView(mSurfaceView);
160 | mWindowVisible = false;
161 | }
162 | }
163 |
164 | @Override
165 | public void updateAspectRatio(int width, int height) {
166 | }
167 | }
168 |
169 | /**
170 | * Implementation for API version 17+.
171 | */
172 | private static final class JellybeanMr1Impl extends OverlayDisplayWindow {
173 | // When true, disables support for moving and resizing the overlay.
174 | // The window is made non-touchable, which makes it possible to
175 | // directly interact with the content underneath.
176 | private static final boolean DISABLE_MOVE_AND_RESIZE = false;
177 |
178 | private final DisplayManager mDisplayManager;
179 | private final WindowManager mWindowManager;
180 |
181 | private final Display mDefaultDisplay;
182 | private final DisplayMetrics mDefaultDisplayMetrics = new DisplayMetrics();
183 |
184 | private View mWindowContent;
185 | private WindowManager.LayoutParams mWindowParams;
186 | private TextureView mTextureView;
187 | private TextView mNameTextView;
188 |
189 | private GestureDetector mGestureDetector;
190 | private ScaleGestureDetector mScaleGestureDetector;
191 |
192 | private boolean mWindowVisible;
193 | private int mWindowX;
194 | private int mWindowY;
195 | private float mWindowScale;
196 |
197 | private float mLiveTranslationX;
198 | private float mLiveTranslationY;
199 | private float mLiveScale = 1.0f;
200 |
201 | public JellybeanMr1Impl(Context context, String name,
202 | int width, int height, int gravity) {
203 | super(context, name, width, height, gravity);
204 |
205 | mDisplayManager = (DisplayManager)context.getSystemService(
206 | Context.DISPLAY_SERVICE);
207 | mWindowManager = (WindowManager)context.getSystemService(
208 | Context.WINDOW_SERVICE);
209 |
210 | mDefaultDisplay = mWindowManager.getDefaultDisplay();
211 | updateDefaultDisplayInfo();
212 |
213 | createWindow();
214 | }
215 |
216 | @Override
217 | public void show() {
218 | if (!mWindowVisible) {
219 | mDisplayManager.registerDisplayListener(mDisplayListener, null);
220 | if (!updateDefaultDisplayInfo()) {
221 | mDisplayManager.unregisterDisplayListener(mDisplayListener);
222 | return;
223 | }
224 |
225 | clearLiveState();
226 | updateWindowParams();
227 | mWindowManager.addView(mWindowContent, mWindowParams);
228 | mWindowVisible = true;
229 | }
230 | }
231 |
232 | @Override
233 | public void dismiss() {
234 | if (mWindowVisible) {
235 | mDisplayManager.unregisterDisplayListener(mDisplayListener);
236 | mWindowManager.removeView(mWindowContent);
237 | mWindowVisible = false;
238 | }
239 | }
240 |
241 | @Override
242 | public void updateAspectRatio(int width, int height) {
243 | if (mWidth * height < mHeight * width) {
244 | mTextureView.getLayoutParams().width = mWidth;
245 | mTextureView.getLayoutParams().height = mWidth * height / width;
246 | } else {
247 | mTextureView.getLayoutParams().width = mHeight * width / height;
248 | mTextureView.getLayoutParams().height = mHeight;
249 | }
250 | relayout();
251 | }
252 |
253 | private void relayout() {
254 | if (mWindowVisible) {
255 | updateWindowParams();
256 | mWindowManager.updateViewLayout(mWindowContent, mWindowParams);
257 | }
258 | }
259 |
260 | private boolean updateDefaultDisplayInfo() {
261 | mDefaultDisplay.getMetrics(mDefaultDisplayMetrics);
262 | return true;
263 | }
264 |
265 | private void createWindow() {
266 | LayoutInflater inflater = LayoutInflater.from(mContext);
267 |
268 | mWindowContent = inflater.inflate(
269 | R.layout.overlay_display_window, null);
270 | mWindowContent.setOnTouchListener(mOnTouchListener);
271 |
272 | mTextureView = (TextureView)mWindowContent.findViewById(
273 | R.id.overlay_display_window_texture);
274 | mTextureView.setPivotX(0);
275 | mTextureView.setPivotY(0);
276 | mTextureView.getLayoutParams().width = mWidth;
277 | mTextureView.getLayoutParams().height = mHeight;
278 | mTextureView.setOpaque(false);
279 | mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
280 |
281 | mNameTextView = (TextView)mWindowContent.findViewById(
282 | R.id.overlay_display_window_title);
283 | mNameTextView.setText(mName);
284 |
285 | mWindowParams = new WindowManager.LayoutParams(
286 | WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
287 | mWindowParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
288 | | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
289 | | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
290 | | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
291 | | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
292 | if (DISABLE_MOVE_AND_RESIZE) {
293 | mWindowParams.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
294 | }
295 | mWindowParams.alpha = WINDOW_ALPHA;
296 | mWindowParams.gravity = Gravity.TOP | Gravity.LEFT;
297 | mWindowParams.setTitle(mName);
298 |
299 | mGestureDetector = new GestureDetector(mContext, mOnGestureListener);
300 | mScaleGestureDetector = new ScaleGestureDetector(mContext, mOnScaleGestureListener);
301 |
302 | // Set the initial position and scale.
303 | // The position and scale will be clamped when the display is first shown.
304 | mWindowX = (mGravity & Gravity.LEFT) == Gravity.LEFT ?
305 | 0 : mDefaultDisplayMetrics.widthPixels;
306 | mWindowY = (mGravity & Gravity.TOP) == Gravity.TOP ?
307 | 0 : mDefaultDisplayMetrics.heightPixels;
308 | Log.d(TAG, mDefaultDisplayMetrics.toString());
309 | mWindowScale = INITIAL_SCALE;
310 |
311 | // calculate and save initial settings
312 | updateWindowParams();
313 | saveWindowParams();
314 | }
315 |
316 | private void updateWindowParams() {
317 | float scale = mWindowScale * mLiveScale;
318 | scale = Math.min(scale, (float)mDefaultDisplayMetrics.widthPixels / mWidth);
319 | scale = Math.min(scale, (float)mDefaultDisplayMetrics.heightPixels / mHeight);
320 | scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));
321 |
322 | float offsetScale = (scale / mWindowScale - 1.0f) * 0.5f;
323 | int width = (int)(mWidth * scale);
324 | int height = (int)(mHeight * scale);
325 | int x = (int)(mWindowX + mLiveTranslationX - width * offsetScale);
326 | int y = (int)(mWindowY + mLiveTranslationY - height * offsetScale);
327 | x = Math.max(0, Math.min(x, mDefaultDisplayMetrics.widthPixels - width));
328 | y = Math.max(0, Math.min(y, mDefaultDisplayMetrics.heightPixels - height));
329 |
330 | if (DEBUG) {
331 | Log.d(TAG, "updateWindowParams: scale=" + scale
332 | + ", offsetScale=" + offsetScale
333 | + ", x=" + x + ", y=" + y
334 | + ", width=" + width + ", height=" + height);
335 | }
336 |
337 | mTextureView.setScaleX(scale);
338 | mTextureView.setScaleY(scale);
339 |
340 | mTextureView.setTranslationX(
341 | (mWidth - mTextureView.getLayoutParams().width) * scale / 2);
342 | mTextureView.setTranslationY(
343 | (mHeight - mTextureView.getLayoutParams().height) * scale / 2);
344 |
345 | mWindowParams.x = x;
346 | mWindowParams.y = y;
347 | mWindowParams.width = width;
348 | mWindowParams.height = height;
349 | }
350 |
351 | private void saveWindowParams() {
352 | mWindowX = mWindowParams.x;
353 | mWindowY = mWindowParams.y;
354 | mWindowScale = mTextureView.getScaleX();
355 | clearLiveState();
356 | }
357 |
358 | private void clearLiveState() {
359 | mLiveTranslationX = 0f;
360 | mLiveTranslationY = 0f;
361 | mLiveScale = 1.0f;
362 | }
363 |
364 | private final DisplayManager.DisplayListener mDisplayListener =
365 | new DisplayManager.DisplayListener() {
366 | @Override
367 | public void onDisplayAdded(int displayId) {
368 | }
369 |
370 | @Override
371 | public void onDisplayChanged(int displayId) {
372 | if (displayId == mDefaultDisplay.getDisplayId()) {
373 | if (updateDefaultDisplayInfo()) {
374 | relayout();
375 | } else {
376 | dismiss();
377 | }
378 | }
379 | }
380 |
381 | @Override
382 | public void onDisplayRemoved(int displayId) {
383 | if (displayId == mDefaultDisplay.getDisplayId()) {
384 | dismiss();
385 | }
386 | }
387 | };
388 |
389 | private final SurfaceTextureListener mSurfaceTextureListener =
390 | new SurfaceTextureListener() {
391 | @Override
392 | public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
393 | int width, int height) {
394 | if (mListener != null) {
395 | mListener.onWindowCreated(new Surface(surfaceTexture));
396 | }
397 | }
398 |
399 | @Override
400 | public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
401 | if (mListener != null) {
402 | mListener.onWindowDestroyed();
403 | }
404 | return true;
405 | }
406 |
407 | @Override
408 | public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
409 | int width, int height) {
410 | }
411 |
412 | @Override
413 | public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
414 | }
415 | };
416 |
417 | private final View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
418 | @Override
419 | public boolean onTouch(View view, MotionEvent event) {
420 | // Work in screen coordinates.
421 | final float oldX = event.getX();
422 | final float oldY = event.getY();
423 | event.setLocation(event.getRawX(), event.getRawY());
424 |
425 | mGestureDetector.onTouchEvent(event);
426 | mScaleGestureDetector.onTouchEvent(event);
427 |
428 | switch (event.getActionMasked()) {
429 | case MotionEvent.ACTION_UP:
430 | case MotionEvent.ACTION_CANCEL:
431 | saveWindowParams();
432 | break;
433 | }
434 |
435 | // Revert to window coordinates.
436 | event.setLocation(oldX, oldY);
437 | return true;
438 | }
439 | };
440 |
441 | private final GestureDetector.OnGestureListener mOnGestureListener =
442 | new GestureDetector.SimpleOnGestureListener() {
443 | @Override
444 | public boolean onScroll(MotionEvent e1, MotionEvent e2,
445 | float distanceX, float distanceY) {
446 | mLiveTranslationX -= distanceX;
447 | mLiveTranslationY -= distanceY;
448 | relayout();
449 | return true;
450 | }
451 | };
452 |
453 | private final ScaleGestureDetector.OnScaleGestureListener mOnScaleGestureListener =
454 | new ScaleGestureDetector.SimpleOnScaleGestureListener() {
455 | @Override
456 | public boolean onScale(ScaleGestureDetector detector) {
457 | mLiveScale *= detector.getScaleFactor();
458 | relayout();
459 | return true;
460 | }
461 | };
462 | }
463 | }
464 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/player/LocalPlayer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.player;
18 |
19 | import android.app.Activity;
20 | import android.app.Presentation;
21 | import android.content.Context;
22 | import android.content.DialogInterface;
23 | import android.media.MediaPlayer;
24 | import android.os.Build;
25 | import android.os.Bundle;
26 | import android.os.Handler;
27 | import android.os.SystemClock;
28 | import android.support.v7.media.MediaItemStatus;
29 | import android.support.v7.media.MediaRouter.RouteInfo;
30 | import android.util.Log;
31 | import android.view.Display;
32 | import android.view.Gravity;
33 | import android.view.Surface;
34 | import android.view.SurfaceHolder;
35 | import android.view.SurfaceView;
36 | import android.view.View;
37 | import android.view.ViewGroup;
38 | import android.view.WindowManager;
39 | import android.widget.FrameLayout;
40 |
41 | import com.example.android.mediarouter.R;
42 |
43 | import java.io.IOException;
44 |
45 | /**
46 | * Handles playback of a single media item using MediaPlayer.
47 | */
48 | public abstract class LocalPlayer extends Player implements
49 | MediaPlayer.OnPreparedListener,
50 | MediaPlayer.OnCompletionListener,
51 | MediaPlayer.OnErrorListener,
52 | MediaPlayer.OnSeekCompleteListener {
53 | private static final String TAG = "LocalPlayer";
54 | private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
55 |
56 | private static final int STATE_IDLE = 0;
57 | private static final int STATE_PLAY_PENDING = 1;
58 | private static final int STATE_READY = 2;
59 | private static final int STATE_PLAYING = 3;
60 | private static final int STATE_PAUSED = 4;
61 |
62 | private final Context mContext;
63 | private final Handler mHandler = new Handler();
64 | private MediaPlayer mMediaPlayer;
65 | private int mState = STATE_IDLE;
66 | private int mSeekToPos;
67 | private int mVideoWidth;
68 | private int mVideoHeight;
69 | private Surface mSurface;
70 | private SurfaceHolder mSurfaceHolder;
71 |
72 | public LocalPlayer(Context context) {
73 | mContext = context;
74 |
75 | // reset media player
76 | reset();
77 | }
78 |
79 | @Override
80 | public boolean isRemotePlayback() {
81 | return false;
82 | }
83 |
84 | @Override
85 | public boolean isQueuingSupported() {
86 | return false;
87 | }
88 |
89 | @Override
90 | public void connect(RouteInfo route) {
91 | if (DEBUG) {
92 | Log.d(TAG, "connecting to: " + route);
93 | }
94 | }
95 |
96 | @Override
97 | public void release() {
98 | if (DEBUG) {
99 | Log.d(TAG, "releasing");
100 | }
101 | // release media player
102 | if (mMediaPlayer != null) {
103 | mMediaPlayer.stop();
104 | mMediaPlayer.release();
105 | mMediaPlayer = null;
106 | }
107 | }
108 |
109 | // Player
110 | @Override
111 | public void play(final PlaylistItem item) {
112 | if (DEBUG) {
113 | Log.d(TAG, "play: item=" + item);
114 | }
115 | reset();
116 | mSeekToPos = (int)item.getPosition();
117 | try {
118 | mMediaPlayer.setDataSource(mContext, item.getUri());
119 | mMediaPlayer.prepareAsync();
120 | } catch (IllegalStateException e) {
121 | Log.e(TAG, "MediaPlayer throws IllegalStateException, uri=" + item.getUri());
122 | } catch (IOException e) {
123 | Log.e(TAG, "MediaPlayer throws IOException, uri=" + item.getUri());
124 | } catch (IllegalArgumentException e) {
125 | Log.e(TAG, "MediaPlayer throws IllegalArgumentException, uri=" + item.getUri());
126 | } catch (SecurityException e) {
127 | Log.e(TAG, "MediaPlayer throws SecurityException, uri=" + item.getUri());
128 | }
129 | if (item.getState() == MediaItemStatus.PLAYBACK_STATE_PLAYING) {
130 | resume();
131 | } else {
132 | pause();
133 | }
134 | }
135 |
136 | @Override
137 | public void seek(final PlaylistItem item) {
138 | if (DEBUG) {
139 | Log.d(TAG, "seek: item=" + item);
140 | }
141 | int pos = (int)item.getPosition();
142 | if (mState == STATE_PLAYING || mState == STATE_PAUSED) {
143 | mMediaPlayer.seekTo(pos);
144 | mSeekToPos = pos;
145 | } else if (mState == STATE_IDLE || mState == STATE_PLAY_PENDING) {
146 | // Seek before onPrepared() arrives,
147 | // need to performed delayed seek in onPrepared()
148 | mSeekToPos = pos;
149 | }
150 | }
151 |
152 | @Override
153 | public void getStatus(final PlaylistItem item, final boolean update) {
154 | if (mState == STATE_PLAYING || mState == STATE_PAUSED) {
155 | // use mSeekToPos if we're currently seeking (mSeekToPos is reset
156 | // when seeking is completed)
157 | item.setDuration(mMediaPlayer.getDuration());
158 | item.setPosition(mSeekToPos > 0 ?
159 | mSeekToPos : mMediaPlayer.getCurrentPosition());
160 | item.setTimestamp(SystemClock.elapsedRealtime());
161 | }
162 | if (update && mCallback != null) {
163 | mCallback.onPlaylistReady();
164 | }
165 | }
166 |
167 | @Override
168 | public void pause() {
169 | if (DEBUG) {
170 | Log.d(TAG, "pause");
171 | }
172 | if (mState == STATE_PLAYING) {
173 | mMediaPlayer.pause();
174 | mState = STATE_PAUSED;
175 | }
176 | }
177 |
178 | @Override
179 | public void resume() {
180 | if (DEBUG) {
181 | Log.d(TAG, "resume");
182 | }
183 | if (mState == STATE_READY || mState == STATE_PAUSED) {
184 | mMediaPlayer.start();
185 | mState = STATE_PLAYING;
186 | } else if (mState == STATE_IDLE){
187 | mState = STATE_PLAY_PENDING;
188 | }
189 | }
190 |
191 | @Override
192 | public void stop() {
193 | if (DEBUG) {
194 | Log.d(TAG, "stop");
195 | }
196 | if (mState == STATE_PLAYING || mState == STATE_PAUSED) {
197 | mMediaPlayer.stop();
198 | mState = STATE_IDLE;
199 | }
200 | }
201 |
202 | @Override
203 | public void enqueue(final PlaylistItem item) {
204 | throw new UnsupportedOperationException("LocalPlayer doesn't support enqueue!");
205 | }
206 |
207 | @Override
208 | public PlaylistItem remove(String iid) {
209 | throw new UnsupportedOperationException("LocalPlayer doesn't support remove!");
210 | }
211 |
212 | //MediaPlayer Listeners
213 | @Override
214 | public void onPrepared(MediaPlayer mp) {
215 | if (DEBUG) {
216 | Log.d(TAG, "onPrepared");
217 | }
218 | mHandler.post(new Runnable() {
219 | @Override
220 | public void run() {
221 | if (mState == STATE_IDLE) {
222 | mState = STATE_READY;
223 | updateVideoRect();
224 | } else if (mState == STATE_PLAY_PENDING) {
225 | mState = STATE_PLAYING;
226 | updateVideoRect();
227 | if (mSeekToPos > 0) {
228 | if (DEBUG) {
229 | Log.d(TAG, "seek to initial pos: " + mSeekToPos);
230 | }
231 | mMediaPlayer.seekTo(mSeekToPos);
232 | }
233 | mMediaPlayer.start();
234 | }
235 | if (mCallback != null) {
236 | mCallback.onPlaylistChanged();
237 | }
238 | }
239 | });
240 | }
241 |
242 | @Override
243 | public void onCompletion(MediaPlayer mp) {
244 | if (DEBUG) {
245 | Log.d(TAG, "onCompletion");
246 | }
247 | mHandler.post(new Runnable() {
248 | @Override
249 | public void run() {
250 | if (mCallback != null) {
251 | mCallback.onCompletion();
252 | }
253 | }
254 | });
255 | }
256 |
257 | @Override
258 | public boolean onError(MediaPlayer mp, int what, int extra) {
259 | if (DEBUG) {
260 | Log.d(TAG, "onError");
261 | }
262 | mHandler.post(new Runnable() {
263 | @Override
264 | public void run() {
265 | if (mCallback != null) {
266 | mCallback.onError();
267 | }
268 | }
269 | });
270 | // return true so that onCompletion is not called
271 | return true;
272 | }
273 |
274 | @Override
275 | public void onSeekComplete(MediaPlayer mp) {
276 | if (DEBUG) {
277 | Log.d(TAG, "onSeekComplete");
278 | }
279 | mHandler.post(new Runnable() {
280 | @Override
281 | public void run() {
282 | mSeekToPos = 0;
283 | if (mCallback != null) {
284 | mCallback.onPlaylistChanged();
285 | }
286 | }
287 | });
288 | }
289 |
290 | protected Context getContext() { return mContext; }
291 | protected MediaPlayer getMediaPlayer() { return mMediaPlayer; }
292 | protected int getVideoWidth() { return mVideoWidth; }
293 | protected int getVideoHeight() { return mVideoHeight; }
294 | protected void setSurface(Surface surface) {
295 | mSurface = surface;
296 | mSurfaceHolder = null;
297 | updateSurface();
298 | }
299 |
300 | protected void setSurface(SurfaceHolder surfaceHolder) {
301 | mSurface = null;
302 | mSurfaceHolder = surfaceHolder;
303 | updateSurface();
304 | }
305 |
306 | protected void removeSurface(SurfaceHolder surfaceHolder) {
307 | if (surfaceHolder == mSurfaceHolder) {
308 | setSurface((SurfaceHolder)null);
309 | }
310 | }
311 |
312 | protected void updateSurface() {
313 | if (mMediaPlayer == null) {
314 | // just return if media player is already gone
315 | return;
316 | }
317 | if (mSurface != null) {
318 | // The setSurface API does not exist until V14+.
319 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
320 | ICSMediaPlayer.setSurface(mMediaPlayer, mSurface);
321 | } else {
322 | throw new UnsupportedOperationException("MediaPlayer does not support "
323 | + "setSurface() on this version of the platform.");
324 | }
325 | } else if (mSurfaceHolder != null) {
326 | mMediaPlayer.setDisplay(mSurfaceHolder);
327 | } else {
328 | mMediaPlayer.setDisplay(null);
329 | }
330 | }
331 |
332 | protected abstract void updateSize();
333 |
334 | private void reset() {
335 | if (mMediaPlayer != null) {
336 | mMediaPlayer.stop();
337 | mMediaPlayer.release();
338 | mMediaPlayer = null;
339 | }
340 | mMediaPlayer = new MediaPlayer();
341 | mMediaPlayer.setOnPreparedListener(this);
342 | mMediaPlayer.setOnCompletionListener(this);
343 | mMediaPlayer.setOnErrorListener(this);
344 | mMediaPlayer.setOnSeekCompleteListener(this);
345 | updateSurface();
346 | mState = STATE_IDLE;
347 | mSeekToPos = 0;
348 | }
349 |
350 | private void updateVideoRect() {
351 | if (mState != STATE_IDLE && mState != STATE_PLAY_PENDING) {
352 | int width = mMediaPlayer.getVideoWidth();
353 | int height = mMediaPlayer.getVideoHeight();
354 | if (width > 0 && height > 0) {
355 | mVideoWidth = width;
356 | mVideoHeight = height;
357 | updateSize();
358 | } else {
359 | Log.e(TAG, "video rect is 0x0!");
360 | mVideoWidth = mVideoHeight = 0;
361 | }
362 | }
363 | }
364 |
365 | private static final class ICSMediaPlayer {
366 | public static final void setSurface(MediaPlayer player, Surface surface) {
367 | player.setSurface(surface);
368 | }
369 | }
370 |
371 | /**
372 | * Handles playback of a single media item using MediaPlayer in SurfaceView
373 | */
374 | public static class SurfaceViewPlayer extends LocalPlayer implements
375 | SurfaceHolder.Callback {
376 | private static final String TAG = "SurfaceViewPlayer";
377 | private RouteInfo mRoute;
378 | private final SurfaceView mSurfaceView;
379 | private final FrameLayout mLayout;
380 | private DemoPresentation mPresentation;
381 |
382 | public SurfaceViewPlayer(Context context) {
383 | super(context);
384 |
385 | mLayout = (FrameLayout)((Activity)context).findViewById(R.id.player);
386 | mSurfaceView = (SurfaceView)((Activity)context).findViewById(R.id.surface_view);
387 |
388 | // add surface holder callback
389 | SurfaceHolder holder = mSurfaceView.getHolder();
390 | holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
391 | holder.addCallback(this);
392 | }
393 |
394 | @Override
395 | public void connect(RouteInfo route) {
396 | super.connect(route);
397 | mRoute = route;
398 | }
399 |
400 | @Override
401 | public void release() {
402 | super.release();
403 |
404 | // dismiss presentation display
405 | if (mPresentation != null) {
406 | Log.i(TAG, "Dismissing presentation because the activity is no longer visible.");
407 | mPresentation.dismiss();
408 | mPresentation = null;
409 | }
410 |
411 | // remove surface holder callback
412 | SurfaceHolder holder = mSurfaceView.getHolder();
413 | holder.removeCallback(this);
414 |
415 | // hide the surface view when SurfaceViewPlayer is destroyed
416 | mSurfaceView.setVisibility(View.GONE);
417 | mLayout.setVisibility(View.GONE);
418 | }
419 |
420 | @Override
421 | public void updatePresentation() {
422 | // Get the current route and its presentation display.
423 | Display presentationDisplay = mRoute != null ? mRoute.getPresentationDisplay() : null;
424 |
425 | // Dismiss the current presentation if the display has changed.
426 | if (mPresentation != null && mPresentation.getDisplay() != presentationDisplay) {
427 | Log.i(TAG, "Dismissing presentation because the current route no longer "
428 | + "has a presentation display.");
429 | mPresentation.dismiss();
430 | mPresentation = null;
431 | }
432 |
433 | // Show a new presentation if needed.
434 | if (mPresentation == null && presentationDisplay != null) {
435 | Log.i(TAG, "Showing presentation on display: " + presentationDisplay);
436 | mPresentation = new DemoPresentation(getContext(), presentationDisplay);
437 | mPresentation.setOnDismissListener(mOnDismissListener);
438 | try {
439 | mPresentation.show();
440 | } catch (WindowManager.InvalidDisplayException ex) {
441 | Log.w(TAG, "Couldn't show presentation! Display was removed in "
442 | + "the meantime.", ex);
443 | mPresentation = null;
444 | }
445 | }
446 |
447 | updateContents();
448 | }
449 |
450 | // SurfaceHolder.Callback
451 | @Override
452 | public void surfaceChanged(SurfaceHolder holder, int format,
453 | int width, int height) {
454 | if (DEBUG) {
455 | Log.d(TAG, "surfaceChanged: " + width + "x" + height);
456 | }
457 | setSurface(holder);
458 | }
459 |
460 | @Override
461 | public void surfaceCreated(SurfaceHolder holder) {
462 | if (DEBUG) {
463 | Log.d(TAG, "surfaceCreated");
464 | }
465 | setSurface(holder);
466 | updateSize();
467 | }
468 |
469 | @Override
470 | public void surfaceDestroyed(SurfaceHolder holder) {
471 | if (DEBUG) {
472 | Log.d(TAG, "surfaceDestroyed");
473 | }
474 | removeSurface(holder);
475 | }
476 |
477 | @Override
478 | protected void updateSize() {
479 | int width = getVideoWidth();
480 | int height = getVideoHeight();
481 | if (width > 0 && height > 0) {
482 | if (mPresentation == null) {
483 | int surfaceWidth = mLayout.getWidth();
484 | int surfaceHeight = mLayout.getHeight();
485 |
486 | // Calculate the new size of mSurfaceView, so that video is centered
487 | // inside the framelayout with proper letterboxing/pillarboxing
488 | ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();
489 | if (surfaceWidth * height < surfaceHeight * width) {
490 | // Black bars on top&bottom, mSurfaceView has full layout width,
491 | // while height is derived from video's aspect ratio
492 | lp.width = surfaceWidth;
493 | lp.height = surfaceWidth * height / width;
494 | } else {
495 | // Black bars on left&right, mSurfaceView has full layout height,
496 | // while width is derived from video's aspect ratio
497 | lp.width = surfaceHeight * width / height;
498 | lp.height = surfaceHeight;
499 | }
500 | Log.i(TAG, "video rect is " + lp.width + "x" + lp.height);
501 | mSurfaceView.setLayoutParams(lp);
502 | } else {
503 | mPresentation.updateSize(width, height);
504 | }
505 | }
506 | }
507 |
508 | private void updateContents() {
509 | // Show either the content in the main activity or the content in the presentation
510 | if (mPresentation != null) {
511 | mLayout.setVisibility(View.GONE);
512 | mSurfaceView.setVisibility(View.GONE);
513 | } else {
514 | mLayout.setVisibility(View.VISIBLE);
515 | mSurfaceView.setVisibility(View.VISIBLE);
516 | }
517 | }
518 |
519 | // Listens for when presentations are dismissed.
520 | private final DialogInterface.OnDismissListener mOnDismissListener =
521 | new DialogInterface.OnDismissListener() {
522 | @Override
523 | public void onDismiss(DialogInterface dialog) {
524 | if (dialog == mPresentation) {
525 | Log.i(TAG, "Presentation dismissed.");
526 | mPresentation = null;
527 | updateContents();
528 | }
529 | }
530 | };
531 |
532 | // Presentation
533 | private final class DemoPresentation extends Presentation {
534 | private SurfaceView mPresentationSurfaceView;
535 |
536 | public DemoPresentation(Context context, Display display) {
537 | super(context, display);
538 | }
539 |
540 | @Override
541 | protected void onCreate(Bundle savedInstanceState) {
542 | // Be sure to call the super class.
543 | super.onCreate(savedInstanceState);
544 |
545 | // Inflate the layout.
546 | setContentView(R.layout.sample_media_router_presentation);
547 |
548 | // Set up the surface view.
549 | mPresentationSurfaceView = (SurfaceView)findViewById(R.id.surface_view);
550 | SurfaceHolder holder = mPresentationSurfaceView.getHolder();
551 | holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
552 | holder.addCallback(SurfaceViewPlayer.this);
553 | Log.i(TAG, "Presentation created");
554 | }
555 |
556 | public void updateSize(int width, int height) {
557 | int surfaceHeight = getWindow().getDecorView().getHeight();
558 | int surfaceWidth = getWindow().getDecorView().getWidth();
559 | ViewGroup.LayoutParams lp = mPresentationSurfaceView.getLayoutParams();
560 | if (surfaceWidth * height < surfaceHeight * width) {
561 | lp.width = surfaceWidth;
562 | lp.height = surfaceWidth * height / width;
563 | } else {
564 | lp.width = surfaceHeight * width / height;
565 | lp.height = surfaceHeight;
566 | }
567 | Log.i(TAG, "Presentation video rect is " + lp.width + "x" + lp.height);
568 | mPresentationSurfaceView.setLayoutParams(lp);
569 | }
570 | }
571 | }
572 |
573 | /**
574 | * Handles playback of a single media item using MediaPlayer in
575 | * OverlayDisplayWindow.
576 | */
577 | public static class OverlayPlayer extends LocalPlayer implements
578 | OverlayDisplayWindow.OverlayWindowListener {
579 | private static final String TAG = "OverlayPlayer";
580 | private final OverlayDisplayWindow mOverlay;
581 |
582 | public OverlayPlayer(Context context) {
583 | super(context);
584 |
585 | mOverlay = OverlayDisplayWindow.create(getContext(),
586 | getContext().getResources().getString(
587 | R.string.sample_media_route_provider_remote),
588 | 1024, 768, Gravity.CENTER);
589 |
590 | mOverlay.setOverlayWindowListener(this);
591 | }
592 |
593 | @Override
594 | public void connect(RouteInfo route) {
595 | super.connect(route);
596 | mOverlay.show();
597 | }
598 |
599 | @Override
600 | public void release() {
601 | super.release();
602 | mOverlay.dismiss();
603 | }
604 |
605 | @Override
606 | protected void updateSize() {
607 | int width = getVideoWidth();
608 | int height = getVideoHeight();
609 | if (width > 0 && height > 0) {
610 | mOverlay.updateAspectRatio(width, height);
611 | }
612 | }
613 |
614 | // OverlayDisplayWindow.OverlayWindowListener
615 | @Override
616 | public void onWindowCreated(Surface surface) {
617 | setSurface(surface);
618 | }
619 |
620 | @Override
621 | public void onWindowCreated(SurfaceHolder surfaceHolder) {
622 | setSurface(surfaceHolder);
623 | }
624 |
625 | @Override
626 | public void onWindowDestroyed() {
627 | setSurface((SurfaceHolder)null);
628 | }
629 | }
630 | }
631 |
--------------------------------------------------------------------------------
/Application/src/main/java/com/example/android/mediarouter/provider/SampleMediaRouteProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 The Android Open Source Project
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.example.android.mediarouter.provider;
18 |
19 | import android.app.PendingIntent;
20 | import android.content.Context;
21 | import android.content.Intent;
22 | import android.content.IntentFilter;
23 | import android.content.IntentFilter.MalformedMimeTypeException;
24 | import android.content.res.Resources;
25 | import android.media.AudioManager;
26 | import android.media.MediaRouter;
27 | import android.net.Uri;
28 | import android.os.Bundle;
29 | import android.support.v7.media.MediaControlIntent;
30 | import android.support.v7.media.MediaRouteDescriptor;
31 | import android.support.v7.media.MediaRouteProvider;
32 | import android.support.v7.media.MediaRouteProviderDescriptor;
33 | import android.support.v7.media.MediaRouter.ControlRequestCallback;
34 | import android.support.v7.media.MediaSessionStatus;
35 | import android.util.Log;
36 |
37 | import com.example.android.mediarouter.player.Player;
38 | import com.example.android.mediarouter.player.PlaylistItem;
39 | import com.example.android.mediarouter.R;
40 | import com.example.android.mediarouter.player.SessionManager;
41 |
42 | import java.util.ArrayList;
43 |
44 | /**
45 | * Demonstrates how to create a custom media route provider.
46 | *
47 | * @see SampleMediaRouteProviderService
48 | */
49 | public final class SampleMediaRouteProvider extends MediaRouteProvider {
50 |
51 | private static final String TAG = "RouteProvider";
52 |
53 | private static final String FIXED_VOLUME_ROUTE_ID = "fixed";
54 | private static final String VARIABLE_VOLUME_BASIC_ROUTE_ID = "variable_basic";
55 | private static final String VARIABLE_VOLUME_QUEUING_ROUTE_ID = "variable_queuing";
56 | private static final String VARIABLE_VOLUME_SESSION_ROUTE_ID = "variable_session";
57 | private static final int VOLUME_MAX = 10;
58 |
59 | /**
60 | * A custom media control intent category for special requests that are
61 | * supported by this provider's routes.
62 | */
63 | public static final String CATEGORY_SAMPLE_ROUTE =
64 | "com.example.android.mediarouteprovider.CATEGORY_SAMPLE_ROUTE";
65 |
66 | /**
67 | * A custom media control intent action for special requests that are
68 | * supported by this provider's routes.
69 | *
70 | * This particular request is designed to return a bundle of not very
71 | * interesting statistics for demonstration purposes.
72 | *
73 | *
74 | * @see #DATA_PLAYBACK_COUNT
75 | */
76 | public static final String ACTION_GET_STATISTICS =
77 | "com.example.android.mediarouteprovider.ACTION_GET_STATISTICS";
78 |
79 | /**
80 | * {@link #ACTION_GET_STATISTICS} result data: Number of times the
81 | * playback action was invoked.
82 | */
83 | public static final String DATA_PLAYBACK_COUNT =
84 | "com.example.android.mediarouteprovider.EXTRA_PLAYBACK_COUNT";
85 |
86 | private static final ArrayList CONTROL_FILTERS_BASIC;
87 | private static final ArrayList CONTROL_FILTERS_QUEUING;
88 | private static final ArrayList CONTROL_FILTERS_SESSION;
89 |
90 | static {
91 | IntentFilter f1 = new IntentFilter();
92 | f1.addCategory(CATEGORY_SAMPLE_ROUTE);
93 | f1.addAction(ACTION_GET_STATISTICS);
94 |
95 | IntentFilter f2 = new IntentFilter();
96 | f2.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
97 | f2.addAction(MediaControlIntent.ACTION_PLAY);
98 | f2.addDataScheme("http");
99 | f2.addDataScheme("https");
100 | f2.addDataScheme("rtsp");
101 | f2.addDataScheme("file");
102 | addDataTypeUnchecked(f2, "video/*");
103 |
104 | IntentFilter f3 = new IntentFilter();
105 | f3.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
106 | f3.addAction(MediaControlIntent.ACTION_SEEK);
107 | f3.addAction(MediaControlIntent.ACTION_GET_STATUS);
108 | f3.addAction(MediaControlIntent.ACTION_PAUSE);
109 | f3.addAction(MediaControlIntent.ACTION_RESUME);
110 | f3.addAction(MediaControlIntent.ACTION_STOP);
111 |
112 | IntentFilter f4 = new IntentFilter();
113 | f4.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
114 | f4.addAction(MediaControlIntent.ACTION_ENQUEUE);
115 | f4.addDataScheme("http");
116 | f4.addDataScheme("https");
117 | f4.addDataScheme("rtsp");
118 | f4.addDataScheme("file");
119 | addDataTypeUnchecked(f4, "video/*");
120 |
121 | IntentFilter f5 = new IntentFilter();
122 | f5.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
123 | f5.addAction(MediaControlIntent.ACTION_REMOVE);
124 |
125 | IntentFilter f6 = new IntentFilter();
126 | f6.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
127 | f6.addAction(MediaControlIntent.ACTION_START_SESSION);
128 | f6.addAction(MediaControlIntent.ACTION_GET_SESSION_STATUS);
129 | f6.addAction(MediaControlIntent.ACTION_END_SESSION);
130 |
131 | CONTROL_FILTERS_BASIC = new ArrayList<>();
132 | CONTROL_FILTERS_BASIC.add(f1);
133 | CONTROL_FILTERS_BASIC.add(f2);
134 | CONTROL_FILTERS_BASIC.add(f3);
135 |
136 | CONTROL_FILTERS_QUEUING = new ArrayList<>(CONTROL_FILTERS_BASIC);
137 | CONTROL_FILTERS_QUEUING.add(f4);
138 | CONTROL_FILTERS_QUEUING.add(f5);
139 |
140 | CONTROL_FILTERS_SESSION = new ArrayList<>(CONTROL_FILTERS_QUEUING);
141 | CONTROL_FILTERS_SESSION.add(f6);
142 | }
143 |
144 | private static void addDataTypeUnchecked(IntentFilter filter, String type) {
145 | try {
146 | filter.addDataType(type);
147 | } catch (MalformedMimeTypeException ex) {
148 | throw new RuntimeException(ex);
149 | }
150 | }
151 |
152 | private int mVolume = 5;
153 | private int mEnqueueCount;
154 |
155 | public SampleMediaRouteProvider(Context context) {
156 | super(context);
157 |
158 | publishRoutes();
159 | }
160 |
161 | @Override
162 | public RouteController onCreateRouteController(String routeId) {
163 | return new SampleRouteController(routeId);
164 | }
165 |
166 | private void publishRoutes() {
167 | Resources r = getContext().getResources();
168 |
169 | MediaRouteDescriptor routeDescriptor1 = new MediaRouteDescriptor.Builder(
170 | FIXED_VOLUME_ROUTE_ID,
171 | r.getString(R.string.fixed_volume_route_name))
172 | .setDescription(r.getString(R.string.sample_route_description))
173 | .addControlFilters(CONTROL_FILTERS_BASIC)
174 | .setPlaybackStream(AudioManager.STREAM_MUSIC)
175 | .setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
176 | .setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_FIXED)
177 | .setVolume(VOLUME_MAX)
178 | .build();
179 |
180 | MediaRouteDescriptor routeDescriptor2 = new MediaRouteDescriptor.Builder(
181 | VARIABLE_VOLUME_BASIC_ROUTE_ID,
182 | r.getString(R.string.variable_volume_basic_route_name))
183 | .setDescription(r.getString(R.string.sample_route_description))
184 | .addControlFilters(CONTROL_FILTERS_BASIC)
185 | .setPlaybackStream(AudioManager.STREAM_MUSIC)
186 | .setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
187 | .setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE)
188 | .setVolumeMax(VOLUME_MAX)
189 | .setVolume(mVolume)
190 | .build();
191 |
192 | MediaRouteDescriptor routeDescriptor3 = new MediaRouteDescriptor.Builder(
193 | VARIABLE_VOLUME_QUEUING_ROUTE_ID,
194 | r.getString(R.string.variable_volume_queuing_route_name))
195 | .setDescription(r.getString(R.string.sample_route_description))
196 | .addControlFilters(CONTROL_FILTERS_QUEUING)
197 | .setPlaybackStream(AudioManager.STREAM_MUSIC)
198 | .setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
199 | .setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE)
200 | .setVolumeMax(VOLUME_MAX)
201 | .setVolume(mVolume)
202 | .build();
203 |
204 | MediaRouteDescriptor routeDescriptor4 = new MediaRouteDescriptor.Builder(
205 | VARIABLE_VOLUME_SESSION_ROUTE_ID,
206 | r.getString(R.string.variable_volume_session_route_name))
207 | .setDescription(r.getString(R.string.sample_route_description))
208 | .addControlFilters(CONTROL_FILTERS_SESSION)
209 | .setPlaybackStream(AudioManager.STREAM_MUSIC)
210 | .setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
211 | .setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE)
212 | .setVolumeMax(VOLUME_MAX)
213 | .setVolume(mVolume)
214 | .build();
215 |
216 | MediaRouteProviderDescriptor providerDescriptor =
217 | new MediaRouteProviderDescriptor.Builder()
218 | .addRoute(routeDescriptor1)
219 | .addRoute(routeDescriptor2)
220 | .addRoute(routeDescriptor3)
221 | .addRoute(routeDescriptor4)
222 | .build();
223 | setDescriptor(providerDescriptor);
224 | }
225 |
226 | private final class SampleRouteController extends MediaRouteProvider.RouteController {
227 | private final String mRouteId;
228 | private final SessionManager mSessionManager = new SessionManager("mrp");
229 | private final Player mPlayer;
230 | private PendingIntent mSessionReceiver;
231 |
232 | public SampleRouteController(String routeId) {
233 | mRouteId = routeId;
234 | mPlayer = Player.create(getContext(), null);
235 | mSessionManager.setPlayer(mPlayer);
236 | mSessionManager.setCallback(new SessionManager.Callback() {
237 | @Override
238 | public void onStatusChanged() {
239 | }
240 |
241 | @Override
242 | public void onItemChanged(PlaylistItem item) {
243 | handleStatusChange(item);
244 | }
245 | });
246 | Log.d(TAG, mRouteId + ": Controller created");
247 | }
248 |
249 | @Override
250 | public void onRelease() {
251 | Log.d(TAG, mRouteId + ": Controller released");
252 | mPlayer.release();
253 | }
254 |
255 | @Override
256 | public void onSelect() {
257 | Log.d(TAG, mRouteId + ": Selected");
258 | mPlayer.connect(null);
259 | }
260 |
261 | @Override
262 | public void onUnselect() {
263 | Log.d(TAG, mRouteId + ": Unselected");
264 | mPlayer.release();
265 | }
266 |
267 | @Override
268 | public void onSetVolume(int volume) {
269 | Log.d(TAG, mRouteId + ": Set volume to " + volume);
270 | if (!mRouteId.equals(FIXED_VOLUME_ROUTE_ID)) {
271 | setVolumeInternal(volume);
272 | }
273 | }
274 |
275 | @Override
276 | public void onUpdateVolume(int delta) {
277 | Log.d(TAG, mRouteId + ": Update volume by " + delta);
278 | if (!mRouteId.equals(FIXED_VOLUME_ROUTE_ID)) {
279 | setVolumeInternal(mVolume + delta);
280 | }
281 | }
282 |
283 | @Override
284 | public boolean onControlRequest(Intent intent, ControlRequestCallback callback) {
285 | Log.d(TAG, mRouteId + ": Received control request " + intent);
286 | String action = intent.getAction();
287 | if (intent.hasCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)) {
288 | boolean success = false;
289 | if (action.equals(MediaControlIntent.ACTION_PLAY)) {
290 | success = handlePlay(intent, callback);
291 | } else if (action.equals(MediaControlIntent.ACTION_ENQUEUE)) {
292 | success = handleEnqueue(intent, callback);
293 | } else if (action.equals(MediaControlIntent.ACTION_REMOVE)) {
294 | success = handleRemove(intent, callback);
295 | } else if (action.equals(MediaControlIntent.ACTION_SEEK)) {
296 | success = handleSeek(intent, callback);
297 | } else if (action.equals(MediaControlIntent.ACTION_GET_STATUS)) {
298 | success = handleGetStatus(intent, callback);
299 | } else if (action.equals(MediaControlIntent.ACTION_PAUSE)) {
300 | success = handlePause(intent, callback);
301 | } else if (action.equals(MediaControlIntent.ACTION_RESUME)) {
302 | success = handleResume(intent, callback);
303 | } else if (action.equals(MediaControlIntent.ACTION_STOP)) {
304 | success = handleStop(intent, callback);
305 | } else if (action.equals(MediaControlIntent.ACTION_START_SESSION)) {
306 | success = handleStartSession(intent, callback);
307 | } else if (action.equals(MediaControlIntent.ACTION_GET_SESSION_STATUS)) {
308 | success = handleGetSessionStatus(intent, callback);
309 | } else if (action.equals(MediaControlIntent.ACTION_END_SESSION)) {
310 | success = handleEndSession(intent, callback);
311 | }
312 | Log.d(TAG, mSessionManager.toString());
313 | return success;
314 | }
315 |
316 | if (action.equals(ACTION_GET_STATISTICS)
317 | && intent.hasCategory(CATEGORY_SAMPLE_ROUTE)) {
318 | Bundle data = new Bundle();
319 | data.putInt(DATA_PLAYBACK_COUNT, mEnqueueCount);
320 | if (callback != null) {
321 | callback.onResult(data);
322 | }
323 | return true;
324 | }
325 | return false;
326 | }
327 |
328 | private void setVolumeInternal(int volume) {
329 | if (volume >= 0 && volume <= VOLUME_MAX) {
330 | mVolume = volume;
331 | Log.d(TAG, mRouteId + ": New volume is " + mVolume);
332 | AudioManager audioManager =
333 | (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
334 | audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
335 | publishRoutes();
336 | }
337 | }
338 |
339 | private boolean handlePlay(Intent intent, ControlRequestCallback callback) {
340 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
341 | if (sid != null && !sid.equals(mSessionManager.getSessionId())) {
342 | Log.d(TAG, "handlePlay fails because of bad sid="+sid);
343 | return false;
344 | }
345 | if (mSessionManager.hasSession()) {
346 | mSessionManager.stop();
347 | }
348 | return handleEnqueue(intent, callback);
349 | }
350 |
351 | private boolean handleEnqueue(Intent intent, ControlRequestCallback callback) {
352 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
353 | if (sid != null && !sid.equals(mSessionManager.getSessionId())) {
354 | Log.d(TAG, "handleEnqueue fails because of bad sid="+sid);
355 | return false;
356 | }
357 |
358 | Uri uri = intent.getData();
359 | if (uri == null) {
360 | Log.d(TAG, "handleEnqueue fails because of bad uri="+uri);
361 | return false;
362 | }
363 |
364 | boolean enqueue = intent.getAction().equals(MediaControlIntent.ACTION_ENQUEUE);
365 | String mime = intent.getType();
366 | long pos = intent.getLongExtra(MediaControlIntent.EXTRA_ITEM_CONTENT_POSITION, 0);
367 | Bundle metadata = intent.getBundleExtra(MediaControlIntent.EXTRA_ITEM_METADATA);
368 | Bundle headers = intent.getBundleExtra(MediaControlIntent.EXTRA_ITEM_HTTP_HEADERS);
369 | PendingIntent receiver = (PendingIntent)intent.getParcelableExtra(
370 | MediaControlIntent.EXTRA_ITEM_STATUS_UPDATE_RECEIVER);
371 |
372 | Log.d(TAG, mRouteId + ": Received " + (enqueue?"enqueue":"play") + " request"
373 | + ", uri=" + uri
374 | + ", mime=" + mime
375 | + ", sid=" + sid
376 | + ", pos=" + pos
377 | + ", metadata=" + metadata
378 | + ", headers=" + headers
379 | + ", receiver=" + receiver);
380 | PlaylistItem item = mSessionManager.add(uri, mime, receiver);
381 | if (callback != null) {
382 | if (item != null) {
383 | Bundle result = new Bundle();
384 | result.putString(MediaControlIntent.EXTRA_SESSION_ID, item.getSessionId());
385 | result.putString(MediaControlIntent.EXTRA_ITEM_ID, item.getItemId());
386 | result.putBundle(MediaControlIntent.EXTRA_ITEM_STATUS,
387 | item.getStatus().asBundle());
388 | callback.onResult(result);
389 | } else {
390 | callback.onError("Failed to open " + uri.toString(), null);
391 | }
392 | }
393 | mEnqueueCount +=1;
394 | return true;
395 | }
396 |
397 | private boolean handleRemove(Intent intent, ControlRequestCallback callback) {
398 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
399 | if (sid == null || !sid.equals(mSessionManager.getSessionId())) {
400 | return false;
401 | }
402 |
403 | String iid = intent.getStringExtra(MediaControlIntent.EXTRA_ITEM_ID);
404 | PlaylistItem item = mSessionManager.remove(iid);
405 | if (callback != null) {
406 | if (item != null) {
407 | Bundle result = new Bundle();
408 | result.putBundle(MediaControlIntent.EXTRA_ITEM_STATUS,
409 | item.getStatus().asBundle());
410 | callback.onResult(result);
411 | } else {
412 | callback.onError("Failed to remove" +
413 | ", sid=" + sid + ", iid=" + iid, null);
414 | }
415 | }
416 | return (item != null);
417 | }
418 |
419 | private boolean handleSeek(Intent intent, ControlRequestCallback callback) {
420 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
421 | if (sid == null || !sid.equals(mSessionManager.getSessionId())) {
422 | return false;
423 | }
424 |
425 | String iid = intent.getStringExtra(MediaControlIntent.EXTRA_ITEM_ID);
426 | long pos = intent.getLongExtra(MediaControlIntent.EXTRA_ITEM_CONTENT_POSITION, 0);
427 | Log.d(TAG, mRouteId + ": Received seek request, pos=" + pos);
428 | PlaylistItem item = mSessionManager.seek(iid, pos);
429 | if (callback != null) {
430 | if (item != null) {
431 | Bundle result = new Bundle();
432 | result.putBundle(MediaControlIntent.EXTRA_ITEM_STATUS,
433 | item.getStatus().asBundle());
434 | callback.onResult(result);
435 | } else {
436 | callback.onError("Failed to seek" +
437 | ", sid=" + sid + ", iid=" + iid + ", pos=" + pos, null);
438 | }
439 | }
440 | return (item != null);
441 | }
442 |
443 | private boolean handleGetStatus(Intent intent, ControlRequestCallback callback) {
444 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
445 | String iid = intent.getStringExtra(MediaControlIntent.EXTRA_ITEM_ID);
446 | Log.d(TAG, mRouteId + ": Received getStatus request, sid=" + sid + ", iid=" + iid);
447 | PlaylistItem item = mSessionManager.getStatus(iid);
448 | if (callback != null) {
449 | if (item != null) {
450 | Bundle result = new Bundle();
451 | result.putBundle(MediaControlIntent.EXTRA_ITEM_STATUS,
452 | item.getStatus().asBundle());
453 | callback.onResult(result);
454 | } else {
455 | callback.onError("Failed to get status" +
456 | ", sid=" + sid + ", iid=" + iid, null);
457 | }
458 | }
459 | return (item != null);
460 | }
461 |
462 | private boolean handlePause(Intent intent, ControlRequestCallback callback) {
463 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
464 | boolean success = (sid != null) && sid.equals(mSessionManager.getSessionId());
465 | mSessionManager.pause();
466 | if (callback != null) {
467 | if (success) {
468 | callback.onResult(new Bundle());
469 | handleSessionStatusChange(sid);
470 | } else {
471 | callback.onError("Failed to pause, sid=" + sid, null);
472 | }
473 | }
474 | return success;
475 | }
476 |
477 | private boolean handleResume(Intent intent, ControlRequestCallback callback) {
478 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
479 | boolean success = (sid != null) && sid.equals(mSessionManager.getSessionId());
480 | mSessionManager.resume();
481 | if (callback != null) {
482 | if (success) {
483 | callback.onResult(new Bundle());
484 | handleSessionStatusChange(sid);
485 | } else {
486 | callback.onError("Failed to resume, sid=" + sid, null);
487 | }
488 | }
489 | return success;
490 | }
491 |
492 | private boolean handleStop(Intent intent, ControlRequestCallback callback) {
493 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
494 | boolean success = (sid != null) && sid.equals(mSessionManager.getSessionId());
495 | mSessionManager.stop();
496 | if (callback != null) {
497 | if (success) {
498 | callback.onResult(new Bundle());
499 | handleSessionStatusChange(sid);
500 | } else {
501 | callback.onError("Failed to stop, sid=" + sid, null);
502 | }
503 | }
504 | return success;
505 | }
506 |
507 | private boolean handleStartSession(Intent intent, ControlRequestCallback callback) {
508 | String sid = mSessionManager.startSession();
509 | Log.d(TAG, "StartSession returns sessionId "+sid);
510 | if (callback != null) {
511 | if (sid != null) {
512 | Bundle result = new Bundle();
513 | result.putString(MediaControlIntent.EXTRA_SESSION_ID, sid);
514 | result.putBundle(MediaControlIntent.EXTRA_SESSION_STATUS,
515 | mSessionManager.getSessionStatus(sid).asBundle());
516 | callback.onResult(result);
517 | mSessionReceiver = (PendingIntent)intent.getParcelableExtra(
518 | MediaControlIntent.EXTRA_SESSION_STATUS_UPDATE_RECEIVER);
519 | handleSessionStatusChange(sid);
520 | } else {
521 | callback.onError("Failed to start session.", null);
522 | }
523 | }
524 | return (sid != null);
525 | }
526 |
527 | private boolean handleGetSessionStatus(Intent intent, ControlRequestCallback callback) {
528 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
529 |
530 | MediaSessionStatus sessionStatus = mSessionManager.getSessionStatus(sid);
531 | if (callback != null) {
532 | if (sessionStatus != null) {
533 | Bundle result = new Bundle();
534 | result.putBundle(MediaControlIntent.EXTRA_SESSION_STATUS,
535 | mSessionManager.getSessionStatus(sid).asBundle());
536 | callback.onResult(result);
537 | } else {
538 | callback.onError("Failed to get session status, sid=" + sid, null);
539 | }
540 | }
541 | return (sessionStatus != null);
542 | }
543 |
544 | private boolean handleEndSession(Intent intent, ControlRequestCallback callback) {
545 | String sid = intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID);
546 | boolean success = (sid != null) && sid.equals(mSessionManager.getSessionId())
547 | && mSessionManager.endSession();
548 | if (callback != null) {
549 | if (success) {
550 | Bundle result = new Bundle();
551 | MediaSessionStatus sessionStatus = new MediaSessionStatus.Builder(
552 | MediaSessionStatus.SESSION_STATE_ENDED).build();
553 | result.putBundle(MediaControlIntent.EXTRA_SESSION_STATUS, sessionStatus.asBundle());
554 | callback.onResult(result);
555 | handleSessionStatusChange(sid);
556 | mSessionReceiver = null;
557 | } else {
558 | callback.onError("Failed to end session, sid=" + sid, null);
559 | }
560 | }
561 | return success;
562 | }
563 |
564 | private void handleStatusChange(PlaylistItem item) {
565 | if (item == null) {
566 | item = mSessionManager.getCurrentItem();
567 | }
568 | if (item != null) {
569 | PendingIntent receiver = item.getUpdateReceiver();
570 | if (receiver != null) {
571 | Intent intent = new Intent();
572 | intent.putExtra(MediaControlIntent.EXTRA_SESSION_ID, item.getSessionId());
573 | intent.putExtra(MediaControlIntent.EXTRA_ITEM_ID, item.getItemId());
574 | intent.putExtra(MediaControlIntent.EXTRA_ITEM_STATUS,
575 | item.getStatus().asBundle());
576 | try {
577 | receiver.send(getContext(), 0, intent);
578 | Log.d(TAG, mRouteId + ": Sending status update from provider");
579 | } catch (PendingIntent.CanceledException e) {
580 | Log.d(TAG, mRouteId + ": Failed to send status update!");
581 | }
582 | }
583 | }
584 | }
585 |
586 | private void handleSessionStatusChange(String sid) {
587 | if (mSessionReceiver != null) {
588 | Intent intent = new Intent();
589 | intent.putExtra(MediaControlIntent.EXTRA_SESSION_ID, sid);
590 | intent.putExtra(MediaControlIntent.EXTRA_SESSION_STATUS,
591 | mSessionManager.getSessionStatus(sid).asBundle());
592 | try {
593 | mSessionReceiver.send(getContext(), 0, intent);
594 | Log.d(TAG, mRouteId + ": Sending session status update from provider");
595 | } catch (PendingIntent.CanceledException e) {
596 | Log.d(TAG, mRouteId + ": Failed to send session status update!");
597 | }
598 | }
599 | }
600 | }
601 | }
602 |
--------------------------------------------------------------------------------