Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectr
roborazzi = { module = "io.github.takahirom.roborazzi:roborazzi", version.ref = "roborazzi" }
roborazzi-compose = { module = "io.github.takahirom.roborazzi:roborazzi-compose", version.ref = "roborazzi" }
roborazzi-rule = { module = "io.github.takahirom.roborazzi:roborazzi-junit-rule", version.ref = "roborazzi" }
tv-compose-foundation = { module = "androidx.tv:tv-foundation", version = "1.0.0-rc01" }
tv-compose-material = { module = "androidx.tv:tv-material", version.ref = "tvComposeMaterial3" }
truth = { module = "com.google.truth:truth", version.ref = "truth" }
validator-push = { module = "com.google.android.wearable.watchface.validator:validator-push", version.ref = "validatorPush" }
Expand Down
3 changes: 3 additions & 0 deletions tv/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ dependencies {
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.tv.compose.material)
implementation(libs.tv.compose.foundation)
implementation(libs.androidx.fragment.ktx)
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.coil.kt.compose)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.test.ext.junit)
Expand Down
43 changes: 43 additions & 0 deletions tv/src/main/java/com/example/tv/ui/AmbientMode.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.tv.ui

import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect

class AmbientModeActivity : ComponentActivity() {

@Composable
private fun KeepScreenOn(enable: Boolean = true) {
val activity = LocalActivity.current
DisposableEffect(enable) {
if (enable) {
// [START android_tv_ambient_mode_on]
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// [END android_tv_ambient_mode_on]
}
onDispose {
// [START android_tv_ambient_mode_off]
activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// [END android_tv_ambient_mode_off]
}
}
}
}
116 changes: 116 additions & 0 deletions tv/src/main/java/com/example/tv/ui/AudioCapabilities.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.tv.ui

import android.media.AudioAttributes
import android.media.AudioDeviceInfo
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi

class AudioCapabilitiesActivity : ComponentActivity() {
private lateinit var audioManager: AudioManager

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun anticipatoryAudioRouteCheck() {
// [START android_tv_audio_capabilities_check]
val format = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_E_AC3)
.setChannelMask(AudioFormat.CHANNEL_OUT_5POINT1)
.setSampleRate(48000)
.build()
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()

if (AudioManager.getDirectPlaybackSupport(format, attributes) !=
AudioManager.DIRECT_PLAYBACK_NOT_SUPPORTED
) {
// The format and attributes are supported for direct playback
// on the currently active routed audio path
} else {
// The format and attributes are NOT supported for direct playback
// on the currently active routed audio path
}
// [END android_tv_audio_capabilities_check]
}

private fun findBestSampleRate(profile: Any): Int = 48000
private fun findBestChannelMask(profile: Any): Int = AudioFormat.CHANNEL_OUT_STEREO

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
// [START android_tv_audio_capabilities_best_format]
private fun findBestAudioFormat(audioAttributes: AudioAttributes): AudioFormat {
val preferredFormats = listOf(
AudioFormat.ENCODING_E_AC3,
AudioFormat.ENCODING_AC3,
AudioFormat.ENCODING_PCM_16BIT,
AudioFormat.ENCODING_DEFAULT
)
val audioProfiles = audioManager.getDirectProfilesForAttributes(audioAttributes)
val bestAudioProfile = preferredFormats.firstNotNullOf { format ->
audioProfiles.firstOrNull { it.format == format }
}
Comment on lines +70 to +72
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of firstNotNullOf will throw a NoSuchElementException if no matching profile is found in audioProfiles. It is safer to use firstNotNullOfOrNull and handle the null case or provide a default value, especially since audioProfiles could be empty depending on the device's capabilities.

Suggested change
val bestAudioProfile = preferredFormats.firstNotNullOf { format ->
audioProfiles.firstOrNull { it.format == format }
}
val bestAudioProfile = preferredFormats.firstNotNullOfOrNull { format ->
audioProfiles.firstOrNull { it.format == format }
} ?: return AudioFormat.Builder().build()

val sampleRate = findBestSampleRate(bestAudioProfile)
val channelMask = findBestChannelMask(bestAudioProfile)
return AudioFormat.Builder()
.setEncoding(bestAudioProfile.format)
.setSampleRate(sampleRate)
.setChannelMask(channelMask)
.build()
}
// [END android_tv_audio_capabilities_best_format]

private fun restartAudioTrack(info: AudioDeviceInfo?) {}
private fun findDefaultAudioDeviceInfo(): AudioDeviceInfo? = null
private fun needsAudioFormatChange(info: AudioDeviceInfo): Boolean = false

fun interceptAudioDeviceChanges() {
val audioPlayer = AudioPlayerWrapper()
val handler = Handler(Looper.getMainLooper())

// [START android_tv_audio_capabilities_intercept]
// audioPlayer is a wrapper around an AudioTrack
// which calls a callback for an AudioTrack write error
audioPlayer.addAudioTrackWriteErrorListener {
// error code can be checked here,
// in case of write error try to recreate the audio track
restartAudioTrack(findDefaultAudioDeviceInfo())
}

audioPlayer.audioTrack.addOnRoutingChangedListener({ audioRouting ->
audioRouting?.routedDevice?.let { audioDeviceInfo ->
// use the updated audio routed device to determine
// what audio format should be used
if (needsAudioFormatChange(audioDeviceInfo)) {
restartAudioTrack(audioDeviceInfo)
}
}
}, handler)
// [END android_tv_audio_capabilities_intercept]
}
}

private class AudioPlayerWrapper {
val audioTrack = AudioTrack.Builder().build()
fun addAudioTrackWriteErrorListener(listener: () -> Unit) {}
}
72 changes: 72 additions & 0 deletions tv/src/main/java/com/example/tv/ui/DisplaySettings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.tv.ui

import android.content.Context
import android.media.MediaFormat
import android.media.quality.MediaQualityManager
import android.media.quality.PictureProfile
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity

// [START android_tv_adjust_display_constants]
const val NAME_STANDARD: String = "standard"
const val NAME_VIVID: String = "vivid"
const val NAME_SPORTS: String = "sports"
const val NAME_GAME: String = "game"
const val NAME_MOVIE: String = "movie"
const val NAME_ENERGY_SAVING: String = "energy_saving"
const val NAME_USER: String = "user"
// [END android_tv_adjust_display_constants]

class DisplaySettingsActivity : ComponentActivity() {
private lateinit var context: Context
private lateinit var mediaCodec: android.media.MediaCodec
private lateinit var mediaQualityManager: MediaQualityManager

fun queryAndApplySportsProfile() {
// [START android_tv_adjust_display_query]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
val mediaQualityManager: MediaQualityManager =
context.getSystemService(MediaQualityManager::class.java)
val profiles = mediaQualityManager.getAvailablePictureProfiles(null)
for (profile in profiles) {
// If we have a system sports profile, apply it to our media codec
if (profile.profileType == PictureProfile.TYPE_SYSTEM &&
profile.name == NAME_SPORTS
) {
val bundle = Bundle().apply {
putParcelable(MediaFormat.KEY_PICTURE_PROFILE_INSTANCE, profile)
}
mediaCodec.setParameters(bundle)
}
}
}
// [END android_tv_adjust_display_query]
}

fun getSpecificProfileByName() {
// [START android_tv_adjust_display_get_specific]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
val profile = mediaQualityManager.getPictureProfile(
PictureProfile.TYPE_SYSTEM, NAME_SPORTS, null
)
}
// [END android_tv_adjust_display_get_specific]
}
}
99 changes: 99 additions & 0 deletions tv/src/main/java/com/example/tv/ui/Hardware.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.tv.ui

import android.annotation.SuppressLint
import androidx.activity.ComponentActivity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.util.Log
import java.io.IOException

// [START android_tv_hardware_check_tv]
const val TAG = "DeviceTypeRuntimeCheck"

// [START_EXCLUDE silent]
class HardwareActivity : ComponentActivity() {
val TAG = "HardwareActivity"

fun checkTvDevice() {

// [END_EXCLUDE]
val isTelevision = packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
if (isTelevision) {
Log.d(TAG, "Running on a TV Device")
} else {
Log.d(TAG, "Running on a non-TV Device")
}
// [END android_tv_hardware_check_tv]
}

fun checkHardwareFeatures() {
// [START android_tv_hardware_check_feature]
// Check whether the telephony hardware feature is available.
if (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
Log.d("HardwareFeatureTest", "Device can make phone calls")
}

// Check whether android.hardware.touchscreen feature is available.
if (packageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) {
Log.d("HardwareFeatureTest", "Device has a touchscreen.")
}
// [END android_tv_hardware_check_feature]
}

fun checkCamera() {
// [START android_tv_hardware_check_camera]
// Check whether the camera hardware feature is available.
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.d("Camera test", "Camera available!")
} else {
Log.d("Camera test", "No camera available. View and edit features only.")
}
// [END android_tv_hardware_check_camera]
}

@SuppressLint("MissingPermission")
fun gpsStaticLocation() {
// [START android_tv_hardware_gps_static]
// Request a static location from the location manager.
val locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val location = locationManager.getLastKnownLocation("static")
if (location == null) {
Log.e(TAG, "Location is null")
return
}

// Attempt to get postal code from the static location object.
val geocoder = Geocoder(this)
val address: Address? =
try {
geocoder.getFromLocation(location.latitude, location.longitude, 1)?.firstOrNull()
?.apply {
Log.d(TAG, postalCode)
}
} catch (e: IOException) {
Log.e(TAG, "Geocoder error", e)
null
}
// [END android_tv_hardware_gps_static]
}
}
Loading
Loading