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 app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,5 @@ dependencies {
implementation(libs.androidx.activity.compose)

implementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.xr.projected)
}
7 changes: 7 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<!-- Indicates that the app makes use of XR spatial APIs, but this isn't a requirement that
should block installing the app -->
<uses-feature android:name="android.software.xr.api.spatial" android:required="false" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

<application
android:allowBackup="true"
Expand All @@ -44,6 +45,12 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".ProjectedActivity"
android:exported="false"
android:requiredDisplayCategory="android.hardware.display.category.XR_PROJECTED"
android:theme="@style/Theme.HelloAndroidXR" />
</application>

</manifest>
215 changes: 215 additions & 0 deletions app/src/main/java/com/example/helloandroidxr/ProjectedActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/*
* Copyright 2024 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.helloandroidxr

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.speech.tts.TextToSpeech
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.xr.projected.ProjectedActivityCompat
import androidx.xr.projected.experimental.ExperimentalProjectedApi
import com.example.helloandroidxr.ui.theme.HelloAndroidXRTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Locale

@OptIn(ExperimentalProjectedApi::class)
class ProjectedActivity : ComponentActivity() {

private var tts: TextToSpeech? = null
private var speechRecognizer: SpeechRecognizer? = null
private var isRecording by mutableStateOf(false)
private var statusText by mutableStateOf("Tap to start command")
private var showExitDialog by mutableStateOf(false)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

tts = TextToSpeech(this) { status ->
if (status == TextToSpeech.SUCCESS) {
tts?.language = Locale.US
speak("Welcome. Tap the glasses touchpad to give a command for changing the properties of the Bug Droid," +
"like its scale, rotation, offset, material color, and material properties.")
}
}

speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this).apply {
setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {
statusText = "Listening..."
}

override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {
isRecording = false
}

override fun onError(error: Int) {
isRecording = false
statusText = "Error: $error. Tap to try again."
}

override fun onResults(results: Bundle?) {
val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
if (!matches.isNullOrEmpty()) {
val command = matches[0]
statusText = "Command captured: $command"
speak("Command has been captured. Tap to record a new command.")
CommandBroadcaster.postCommand(command)
}
isRecording = false
}

override fun onPartialResults(partialResults: Bundle?) {}
override fun onEvent(eventType: Int, params: Bundle?) {}
})
}

onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
showExitDialog = true
}
})

setContent {
HelloAndroidXRTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Box(
modifier = Modifier
.fillMaxSize()
.clickable {
if (isRecording) {
stopListening()
} else {
startListening()
}
},
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = statusText,
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(16.dp)
)
if (isRecording) {
Text(text = "Tap to finish", style = MaterialTheme.typography.bodyLarge)
}
}

if (showExitDialog) {
AlertDialog(
onDismissRequest = { showExitDialog = false },
title = { Text("Exit") },
text = { Text("Do you really want to exit the projected activity?") },
confirmButton = {
TextButton(onClick = {
showExitDialog = false
finish()
}) {
Text("Yes")
}
},
dismissButton = {
TextButton(onClick = { showExitDialog = false }) {
Text("No")
}
}
)
}
}
}
}
}
}

private fun startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
lifecycleScope.launch(Dispatchers.IO) {
ProjectedActivityCompat.requestPermissions(this@ProjectedActivity, arrayOf(Manifest.permission.RECORD_AUDIO), 101)
}
} else {
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 101)
}
return
}

val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
}
speechRecognizer?.startListening(intent)
isRecording = true
}

private fun stopListening() {
speechRecognizer?.stopListening()
isRecording = false
}

private fun speak(text: String) {
tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
}

override fun onDestroy() {
super.onDestroy()
tts?.shutdown()
speechRecognizer?.destroy()
}
}

object CommandBroadcaster {
private var callback: ((String) -> Unit)? = null
fun setCallback(cb: (String) -> Unit) {
callback = cb
}
fun postCommand(command: String) {
callback?.invoke(command)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import android.content.Intent
import android.os.Build
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.xr.projected.ProjectedContext
import androidx.xr.projected.experimental.ExperimentalProjectedApi
import com.example.helloandroidxr.ProjectedActivity
import com.example.helloandroidxr.CommandBroadcaster
import kotlinx.coroutines.Dispatchers
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.dimensionResource
Expand Down Expand Up @@ -100,6 +109,12 @@ fun HelloAndroidXRApp() {
}

val uiState by viewModel.uiState.collectAsState()

LaunchedEffect(Unit) {
CommandBroadcaster.setCallback { command ->
viewModel.updateCapturedCommand(command)
}
}
if (LocalSpatialCapabilities.current.isSpatialUiEnabled) {
SpatialLayout(
primaryContent = {
Expand Down Expand Up @@ -135,7 +150,8 @@ fun HelloAndroidXRApp() {
modifier = Modifier.height(240.dp),
showBugdroid = uiState.showBugdroid,
onSliderGroupSelected = viewModel::updateShownSliderGroup,
onResetModel = viewModel::resetModel
onResetModel = viewModel::resetModel,
capturedCommand = uiState.capturedCommand
)
BlockOfContentTwo(
uiState = uiState,
Expand Down Expand Up @@ -388,7 +404,8 @@ private fun BlockOfContentOne(
modifier: Modifier = Modifier,
showBugdroid: Boolean,
onSliderGroupSelected: (SliderGroup) -> Unit,
onResetModel: () -> Unit
onResetModel: () -> Unit,
capturedCommand: String = ""
) {
if (LocalSpatialCapabilities.current.isContent3dEnabled && showBugdroid) {
BugdroidControls(
Expand All @@ -400,10 +417,21 @@ private fun BlockOfContentOne(
modifier = modifier
)
} else {
TextPane(stringResource(R.string.block_of_content_1), modifier = modifier.fillMaxHeight())
Column(modifier = modifier.fillMaxHeight()) {
TextPane(stringResource(R.string.block_of_content_1), modifier = Modifier.weight(1f))

if (capturedCommand.isNotEmpty()) {
Text(
text = "Last command: $capturedCommand",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(16.dp)
)
}
}
}
}

@OptIn(ExperimentalProjectedApi::class)
@Composable
private fun BlockOfContentTwo(
modifier: Modifier = Modifier,
Expand All @@ -427,7 +455,31 @@ private fun BlockOfContentTwo(
modifier = modifier
)
} else {
TextPane(stringResource(R.string.block_of_content_2), modifier = modifier.fillMaxHeight())
Box(modifier = modifier.fillMaxHeight()) {
TextPane(stringResource(R.string.block_of_content_2), modifier = Modifier.fillMaxSize())

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
val context = LocalContext.current
val isGlassesConnected by remember(context) {
ProjectedContext.isProjectedDeviceConnected(context, Dispatchers.Default)
}.collectAsState(initial = false)

if (isGlassesConnected) {
ExtendedFloatingActionButton(
onClick = {
val options = ProjectedContext.createProjectedActivityOptions(context)
val intent = Intent(context, ProjectedActivity::class.java)
context.startActivity(intent, options.toBundle())
},
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp)
) {
Text("Launch on Glasses")
}
}
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ data class BugdroidUiState(
val animateBugdroid: Boolean = false,
val visibleSliderGroup: SliderGroup = SliderGroup.NONE,
val modelTransform: ModelTransform = ModelTransform(),
val capturedCommand: String = "",
)

class BugdroidViewModel : ViewModel() {
Expand All @@ -135,6 +136,10 @@ class BugdroidViewModel : ViewModel() {
private var gltfEntity: GltfModelEntity? = null
private var pbrMaterial: KhronosPbrMaterial? = null

fun updateCapturedCommand(command: String) {
_uiState.update { it.copy(capturedCommand = command) }
}

fun initSession(session: Session) {
if (this.xrSession == session) return
this.xrSession = session
Expand Down
3 changes: 2 additions & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ activityCompose = "1.13.0"
composeBom = "2026.08.00"
material = "1.14.0"
adaptiveAndroid = "1.3.0"
projected = "1.0.0-alpha12"

[libraries]
androidx-arcore = { module = "androidx.xr.arcore:arcore", version.ref = "arcore" }
Expand All @@ -25,7 +26,7 @@ androidx-activity-compose = { group = "androidx.activity", name = "activity-comp
androidx-compose-runtime = { module = "androidx.compose.runtime:runtime", version.ref = "androidx-runtime" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-adaptive-android = { group = "androidx.compose.material3.adaptive", name = "adaptive-android", version.ref = "adaptiveAndroid" }

androidx-xr-projected = { module = "androidx.xr.projected:projected", version.ref = "projected" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
Loading