diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..e69de29 diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore new file mode 100644 index 0000000..66eaea9 --- /dev/null +++ b/buildSrc/.gitignore @@ -0,0 +1,2 @@ +.gradle +/build \ No newline at end of file diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..d7c0465 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + `kotlin-dsl` + `kotlin-dsl-precompiled-script-plugins` +} + +dependencies { + implementation(libs.jetbrains.kotlin) + implementation( libs.android.build.gradle) +} + +gradlePlugin { + plugins { + create("android-library-module") { + id = "android-library-module" + implementationClass = "gradlePlugins.AndroidLibraryPlugin" + } + create("android-application-module"){ + id = "android-application-module" + implementationClass = "gradlePlugins.AndroidApplicationPlugin" + } + } +} \ No newline at end of file diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 0000000..96d7b44 --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,34 @@ +pluginManagement { + + repositories { + gradlePluginPortal() + google() + mavenCentral() + mavenLocal() + } + buildscript { + repositories { + mavenCentral() +// maven { +// url = uri("https://storage.googleapis.com/r8-releases/raw") +// } + } +// dependencies { +// classpath("com.android.tools:r8:8.2.42") +// } + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } + versionCatalogs { + create("libs") { + from(files("../gradle/libs.versions.toml")) + } + } +} + +rootProject.name = "buildSrc" diff --git a/buildSrc/src/main/kotlin/gradlePlugins/AndroidApplicationPlugin.kt b/buildSrc/src/main/kotlin/gradlePlugins/AndroidApplicationPlugin.kt new file mode 100644 index 0000000..8b20610 --- /dev/null +++ b/buildSrc/src/main/kotlin/gradlePlugins/AndroidApplicationPlugin.kt @@ -0,0 +1,73 @@ +package gradlePlugins + +import com.android.build.gradle.BaseExtension +import org.gradle.api.JavaVersion +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.VersionCatalog +import org.gradle.api.artifacts.VersionCatalogsExtension +import org.gradle.kotlin.dsl.dependencies +import org.gradle.kotlin.dsl.withType +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +class AndroidApplicationPlugin : Plugin { + + private val Project.android: BaseExtension + get() = extensions.findByName("android") as? BaseExtension + ?: error("Not an Android module: $name") + + override fun apply(project: Project) = + with(project) { + val libs = project.rootProject + .extensions + .getByType(VersionCatalogsExtension::class.java) + .named("libs") + applyPlugins() + androidConfig(libs) + dependenciesConfig() + } + + private fun Project.applyPlugins() { + plugins.run { + apply("com.android.application") + apply("org.jetbrains.kotlin.android") + } + } + + private fun Project.androidConfig(libs: VersionCatalog) { + val javaVer = JavaVersion.valueOf(libs.findVersion("java_compatibility").get().displayName) + android.run { + compileSdkVersion( libs.findVersion("compile_sdk").get().displayName.toInt()) + defaultConfig { + minSdk = libs.findVersion("compile_sdk").get().displayName.toInt() + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + targetSdk = libs.findVersion("compile_sdk").get().displayName.toInt() + versionCode = libs.findVersion("versionCode").get().displayName.toInt() + versionName = libs.findVersion("versionName").get().displayName + } + buildTypes { + getByName("debug") { + isMinifyEnabled = false + } + getByName("release") { + isMinifyEnabled= false + consumerProguardFiles("consumer-rules.pro") + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { +// isCoreLibraryDesugaringEnabled = true + sourceCompatibility = javaVer + targetCompatibility = javaVer + } + tasks.withType().configureEach { + kotlinOptions.jvmTarget = javaVer.toString() + } + } + } + private fun Project.dependenciesConfig() { + dependencies { +// "coreLibraryDesugaring"( "com.android.tools:desugar_jdk_libs:${ver.android.desugar}") + } + } +} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/gradlePlugins/AndroidLibraryPlugin.kt b/buildSrc/src/main/kotlin/gradlePlugins/AndroidLibraryPlugin.kt new file mode 100644 index 0000000..e25fe22 --- /dev/null +++ b/buildSrc/src/main/kotlin/gradlePlugins/AndroidLibraryPlugin.kt @@ -0,0 +1,71 @@ +package gradlePlugins + +import com.android.build.gradle.BaseExtension +import org.gradle.api.JavaVersion +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.VersionCatalog +import org.gradle.api.artifacts.VersionCatalogsExtension +import org.gradle.kotlin.dsl.dependencies +import org.gradle.kotlin.dsl.withType +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +class AndroidLibraryPlugin : Plugin { + + private val Project.android: BaseExtension + get() = extensions.findByName("android") as? BaseExtension + ?: error("Not an Android module: $name") + + override fun apply(project: Project) = + with(project) { + val libs = project.rootProject + .extensions + .getByType(VersionCatalogsExtension::class.java) + .named("libs") + applyPlugins() + androidConfig(libs) + dependenciesConfig() + } + + private fun Project.applyPlugins() { + plugins.run { + apply("com.android.library") +// apply("kotlin-multiplatform") + apply("org.jetbrains.kotlin.android") + } + } + + private fun Project.androidConfig(libs: VersionCatalog) { + val javaVer = JavaVersion.valueOf(libs.findVersion("java_compatibility").get().displayName) + android.run { + compileSdkVersion( libs.findVersion("compile_sdk").get().displayName.toInt()) + defaultConfig { + minSdk = libs.findVersion("min_sdk").get().displayName.toInt() + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + getByName("debug") { + isMinifyEnabled = false + } + getByName("release") { + isMinifyEnabled= false + consumerProguardFiles("consumer-rules.pro") + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { +// isCoreLibraryDesugaringEnabled = true + sourceCompatibility = javaVer + targetCompatibility = javaVer + } + tasks.withType().configureEach { + kotlinOptions.jvmTarget = javaVer.toString() + } + } + } + private fun Project.dependenciesConfig() { + dependencies { +// "coreLibraryDesugaring"( "com.android.tools:desugar_jdk_libs:${ver.android.desugar}") + } + } +} \ No newline at end of file diff --git a/car-lib/CarGearViewerKotlin/automotive/build.gradle b/car-lib/CarGearViewerKotlin/automotive/build.gradle deleted file mode 100644 index 99cd9ee..0000000 --- a/car-lib/CarGearViewerKotlin/automotive/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2020 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 - * - * http://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. - */ - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply plugin: 'kotlin-android-extensions' - -android { - compileSdkVersion 29 - buildToolsVersion "29.0.3" - - defaultConfig { - applicationId "com.example.cargearviewer" - minSdkVersion 28 - targetSdkVersion 29 - versionCode 1 - versionName "1.0" - - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } - - // android.car exists since Android 10 (API level 29) Revision 5. - useLibrary 'android.car' -} - -dependencies { - implementation fileTree(include: ['*.jar'], dir: 'libs') - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - implementation 'androidx.core:core-ktx:1.3.1' -} diff --git a/car-lib/CarGearViewerKotlin/automotive/build.gradle.kts b/car-lib/CarGearViewerKotlin/automotive/build.gradle.kts new file mode 100644 index 0000000..0d2ef83 --- /dev/null +++ b/car-lib/CarGearViewerKotlin/automotive/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + kotlin("android") + id("android-application-module") +} + +android { + namespace = "com.example.cargearviewer" + defaultConfig { + applicationId = "com.example.cargearviewer" + } + // android.car exists since Android 10 (API level 29) Revision 5. + useLibrary("android.car") +} + +dependencies { + implementation(libs.androidx.core.ktx) + } +//dependencies { +// implementation fileTree(include: ['*.jar'], dir: 'libs') +// implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +// implementation 'androidx.core:core-ktx:1.3.1' +//} diff --git a/car-lib/CarGearViewerKotlin/automotive/src/main/AndroidManifest.xml b/car-lib/CarGearViewerKotlin/automotive/src/main/AndroidManifest.xml index 01dd611..0366d7e 100644 --- a/car-lib/CarGearViewerKotlin/automotive/src/main/AndroidManifest.xml +++ b/car-lib/CarGearViewerKotlin/automotive/src/main/AndroidManifest.xml @@ -28,7 +28,8 @@ android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@android:style/Theme.DeviceDefault.NoActionBar"> - + diff --git a/car-lib/CarGearViewerKotlin/gradle/wrapper/gradle-wrapper.jar b/car-lib/CarGearViewerKotlin/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index f6b961f..0000000 Binary files a/car-lib/CarGearViewerKotlin/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/car-lib/CarGearViewerKotlin/settings.gradle b/car-lib/CarGearViewerKotlin/settings.gradle deleted file mode 100644 index 88ceeec..0000000 --- a/car-lib/CarGearViewerKotlin/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -include ':automotive' diff --git a/car_app_library/.gitignore b/car_app_library/.gitignore new file mode 100644 index 0000000..676fe2b --- /dev/null +++ b/car_app_library/.gitignore @@ -0,0 +1,16 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +/java_pid17944.hprof diff --git a/car_app_library/build.gradle b/car_app_library/build.gradle deleted file mode 100644 index 6a2b974..0000000 --- a/car_app_library/build.gradle +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2020 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 - * - * http://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. - */ - -buildscript { - - repositories { - google() - jcenter() - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:7.0.4' - - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files - } -} - -allprojects { - tasks.withType(JavaCompile) { - options.compilerArgs << "-Xlint:deprecation" - } - - repositories { - google() - jcenter() - mavenCentral() - } -} - -task clean(type: Delete) { - delete rootProject.buildDir -} - diff --git a/car_app_library/gradle.properties b/car_app_library/gradle.properties deleted file mode 100644 index 4204531..0000000 --- a/car_app_library/gradle.properties +++ /dev/null @@ -1,33 +0,0 @@ -# -# Copyright 2020 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 -# -# http://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. -# - -# Properties that are copied from main properties file -# We set playground properties in two steps: -# * This file is linked into github_gradle.properties under the project and limited to -# just copying properties from the androidx properties file without any change. -# Its integrity is validated as part of the buildOnServer task in AndroidX. -# (validatePlaygroundGradleProperties task) -# * Additional settings are in playground.properties which are loaded dynamically -# This separation is necessary to ensure gradle can read certain properties -# at configuration time. - -android.useAndroidX=true -# Disable features we do not use -android.defaults.buildfeatures.aidl=false -android.defaults.buildfeatures.buildconfig=false -android.defaults.buildfeatures.renderscript=false -android.defaults.buildfeatures.resvalues=false -android.defaults.buildfeatures.shaders=false diff --git a/car_app_library/helloworld/automotive/.gitignore b/car_app_library/helloworld/automotive/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/helloworld/automotive/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/helloworld/automotive/build.gradle b/car_app_library/helloworld/automotive/build.gradle deleted file mode 100644 index 7fe19aa..0000000 --- a/car_app_library/helloworld/automotive/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2020 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 - * - * http://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. - */ - -apply plugin: 'com.android.application' - -android { - compileSdk 32 - - defaultConfig { - applicationId "androidx.car.app.sample.helloworld" - minSdkVersion 29 - targetSdkVersion 32 - versionCode 1 - versionName "1.0" - } - - buildTypes { - release { - // Enables code shrinking, obfuscation, and optimization. - minifyEnabled true - proguardFiles getDefaultProguardFile( - 'proguard-android-optimize.txt'), - 'proguard-rules.pro' - } - } - - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.helloworld" -} - -dependencies { - implementation "androidx.car.app:app-automotive:1.2.0-rc01" - implementation project(":helloworld:common") -} diff --git a/car_app_library/helloworld/automotive/build.gradle.kts b/car_app_library/helloworld/automotive/build.gradle.kts new file mode 100644 index 0000000..e166ab5 --- /dev/null +++ b/car_app_library/helloworld/automotive/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + kotlin("android") + id("android-application-module") +} + +android { + namespace = "androidx.car.app.sample.helloworld" + defaultConfig { + applicationId = "androidx.car.app.sample.helloworld" + } +} + +dependencies { + implementation(libs.androidx.car.automotive) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.appcompat) + implementation(project(":car_app_library:helloworld:shared")) + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} \ No newline at end of file diff --git a/car_app_library/helloworld/common/build.gradle b/car_app_library/helloworld/common/build.gradle deleted file mode 100644 index e5cf456..0000000 --- a/car_app_library/helloworld/common/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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. - */ - -apply plugin: 'com.android.library' - -android { - compileSdk 32 - - defaultConfig { - minSdkVersion 23 - targetSdkVersion 32 - versionCode 1 - versionName "1.0" - } - - buildTypes { - release { - // Enables code shrinking, obfuscation, and optimization. - minifyEnabled true - proguardFiles getDefaultProguardFile( - 'proguard-android-optimize.txt'), - 'proguard-rules.pro' - } - } - - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.helloworld.common" -} - -dependencies { - implementation "androidx.car.app:app:1.2.0-rc01" -} - - diff --git a/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.java b/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.java deleted file mode 100644 index 9ca8d94..0000000 --- a/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.helloworld.common; - -import androidx.annotation.NonNull; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.Pane; -import androidx.car.app.model.PaneTemplate; -import androidx.car.app.model.Row; -import androidx.car.app.model.Template; - -/** - * A screen that shows a simple "Hello World!" message. - * - *

See {@link HelloWorldService} for the app's entry point to the car host. - */ -public class HelloWorldScreen extends Screen { - public HelloWorldScreen(@NonNull CarContext carContext) { - super(carContext); - } - - @NonNull - @Override - public Template onGetTemplate() { - Row row = new Row.Builder().setTitle("Hello AndroidX!").build(); - return new PaneTemplate.Builder(new Pane.Builder().addRow(row).build()) - .setHeaderAction(Action.APP_ICON) - .build(); - } -} diff --git a/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.java b/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.java deleted file mode 100644 index d8de977..0000000 --- a/car_app_library/helloworld/common/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.helloworld.common; - -import android.content.Intent; -import android.content.pm.ApplicationInfo; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarAppService; -import androidx.car.app.Screen; -import androidx.car.app.Session; -import androidx.car.app.SessionInfo; -import androidx.car.app.validation.HostValidator; - -/** - * Entry point for the hello world app. - * - *

{@link CarAppService} is the main interface between the app and the car host. For more - * details, see the Android for - * Cars Library developer guide. - */ -public final class HelloWorldService extends CarAppService { - - public HelloWorldService() { - // Exported services must have an empty public constructor. - } - - @Override - @NonNull - public Session onCreateSession(@NonNull SessionInfo sessionInfo) { - return new Session() { - @Override - @NonNull - public Screen onCreateScreen(@Nullable Intent intent) { - return new HelloWorldScreen(getCarContext()); - } - }; - } - - @NonNull - @Override - public HostValidator createHostValidator() { - if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { - return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR; - } else { - return new HostValidator.Builder(getApplicationContext()) - .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample) - .build(); - } - } -} diff --git a/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldScreenTest.java b/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldScreenTest.java deleted file mode 100644 index 6134205..0000000 --- a/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldScreenTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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 androidx.car.app.sample.helloworld.common; - -import static com.google.common.truth.Truth.assertThat; - -import androidx.car.app.model.PaneTemplate; -import androidx.car.app.model.Row; -import androidx.car.app.testing.TestCarContext; -import androidx.test.core.app.ApplicationProvider; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.internal.DoNotInstrument; - -import java.util.List; - -/** - * A sample test on {@link HelloWorldScreen}. - * - *

Demonstrating the usage of {@link TestCarContext} and validating that the returned - * {@link androidx.car.app.model.Template} has the expected contents. - */ -@RunWith(RobolectricTestRunner.class) -@DoNotInstrument -public class HelloWorldScreenTest { - private final TestCarContext mTestCarContext = - TestCarContext.createCarContext(ApplicationProvider.getApplicationContext()); - - @Test - public void getTemplate_containsExpectedRow() { - HelloWorldScreen screen = new HelloWorldScreen(mTestCarContext); - PaneTemplate template = (PaneTemplate) screen.onGetTemplate(); - - List rows = template.getPane().getRows(); - assertThat(rows).hasSize(1); - assertThat(rows.get(0)).isEqualTo(new Row.Builder().setTitle("Hello AndroidX!").build()); - } -} diff --git a/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldSessionTest.java b/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldSessionTest.java deleted file mode 100644 index e1e2be1..0000000 --- a/car_app_library/helloworld/common/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldSessionTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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 androidx.car.app.sample.helloworld.common; - -import static com.google.common.truth.Truth.assertThat; - -import android.content.ComponentName; -import android.content.Intent; - -import androidx.car.app.Screen; -import androidx.car.app.Session; -import androidx.car.app.SessionInfo; -import androidx.car.app.testing.SessionController; -import androidx.car.app.testing.TestCarContext; -import androidx.car.app.testing.TestScreenManager; -import androidx.lifecycle.Lifecycle; -import androidx.test.core.app.ApplicationProvider; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.Robolectric; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.internal.DoNotInstrument; - -/** - * A sample test on the session instance from {@link HelloWorldService}. - * - *

Demonstrating the usage of {@link SessionController} and validating that the session is - * pushing the expected screen when created. - */ -@RunWith(RobolectricTestRunner.class) -@DoNotInstrument -public class HelloWorldSessionTest { - private final TestCarContext mTestCarContext = - TestCarContext.createCarContext(ApplicationProvider.getApplicationContext()); - - @Test - public void onCreateScreen_returnsExpectedScreen() { - HelloWorldService service = Robolectric.setupService(HelloWorldService.class); - Session session = service.onCreateSession(SessionInfo.DEFAULT_SESSION_INFO); - SessionController controller = - new SessionController(session, mTestCarContext, - new Intent().setComponent( - new ComponentName(mTestCarContext, HelloWorldService.class))); - controller.moveToState(Lifecycle.State.CREATED); - - Screen screenCreated = - mTestCarContext.getCarService(TestScreenManager.class).getScreensPushed().get(0); - assertThat(screenCreated).isInstanceOf(HelloWorldScreen.class); - } - -} diff --git a/car_app_library/helloworld/mobile/.gitignore b/car_app_library/helloworld/mobile/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/helloworld/mobile/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/helloworld/mobile/build.gradle b/car_app_library/helloworld/mobile/build.gradle deleted file mode 100644 index f836662..0000000 --- a/car_app_library/helloworld/mobile/build.gradle +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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. - */ - -apply plugin: 'com.android.application' - -android { - compileSdk 32 - - defaultConfig { - applicationId "androidx.car.app.sample.helloworld" - minSdkVersion 23 - targetSdkVersion 32 - versionCode 1 - versionName "1.0" - } - - buildTypes { - release { - // Enables code shrinking, obfuscation, and optimization. - minifyEnabled true - proguardFiles getDefaultProguardFile( - 'proguard-android-optimize.txt'), - 'proguard-rules.pro' - } - } - - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.helloworld" -} - -dependencies { - implementation "androidx.car.app:app-projected:1.2.0-rc01" - implementation project(":helloworld:common") -} - - diff --git a/car_app_library/helloworld/mobile/build.gradle.kts b/car_app_library/helloworld/mobile/build.gradle.kts new file mode 100644 index 0000000..cce944c --- /dev/null +++ b/car_app_library/helloworld/mobile/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + kotlin("android") + id("android-application-module") +} + +android { + namespace = "androidx.car.app.sample.helloworld" + defaultConfig { + applicationId = "androidx.car.app.sample.helloworld" + } +} + +dependencies { + implementation(libs.androidx.car.projected) + implementation(project(":car_app_library:helloworld:shared")) + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + } \ No newline at end of file diff --git a/car_app_library/helloworld/shared/.gitignore b/car_app_library/helloworld/shared/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/helloworld/shared/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/helloworld/shared/build.gradle.kts b/car_app_library/helloworld/shared/build.gradle.kts new file mode 100644 index 0000000..6c5ab3b --- /dev/null +++ b/car_app_library/helloworld/shared/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + kotlin("android") + id("android-library-module") +} + +android { + namespace = "androidx.car.app.sample.helloworld.common" +} + +dependencies { + implementation( libs.androidx.core) + implementation( libs.androidx.car.app) +} \ No newline at end of file diff --git a/car_app_library/helloworld/common/src/main/AndroidManifest.xml b/car_app_library/helloworld/shared/src/main/AndroidManifest.xml similarity index 100% rename from car_app_library/helloworld/common/src/main/AndroidManifest.xml rename to car_app_library/helloworld/shared/src/main/AndroidManifest.xml diff --git a/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.kt b/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.kt new file mode 100644 index 0000000..75fcc1b --- /dev/null +++ b/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldScreen.kt @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 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 + * + * http://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 androidx.car.app.sample.helloworld.common + +import androidx.car.app.CarContext +import androidx.car.app.Screen +import androidx.car.app.model.Action +import androidx.car.app.model.Pane +import androidx.car.app.model.PaneTemplate +import androidx.car.app.model.Row +import androidx.car.app.model.Template + +/** + * A screen that shows a simple "Hello World!" message. + * + * + * See [HelloWorldService] for the app's entry point to the car host. + */ +class HelloWorldScreen(carContext: CarContext) : Screen(carContext) { + override fun onGetTemplate(): Template { + val row = Row.Builder().setTitle("Hello AndroidX!").build() + return PaneTemplate.Builder(Pane.Builder().addRow(row).build()) + .setHeaderAction(Action.APP_ICON) + .build() + } +} diff --git a/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.kt b/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.kt new file mode 100644 index 0000000..ebd298d --- /dev/null +++ b/car_app_library/helloworld/shared/src/main/java/androidx/car/app/sample/helloworld/common/HelloWorldService.kt @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2021 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 + * + * http://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 androidx.car.app.sample.helloworld.common + +import android.content.Intent +import android.content.pm.ApplicationInfo +import androidx.car.app.CarAppService +import androidx.car.app.R +import androidx.car.app.Screen +import androidx.car.app.Session +import androidx.car.app.validation.HostValidator + +//import androidx.car.app.SessionInfo; +/** + * Entry point for the hello world app. + * + * + * [CarAppService] is the main interface between the app and the car host. For more + * details, see the [Android for + * Cars Library developer guide](https://developer.android.com/training/cars/navigation). + */ +class HelloWorldService : CarAppService() { + // @Override + // public Session onCreateSession(@NonNull SessionInfo sessionInfo) { + override fun onCreateSession(): Session { + return object : Session() { + override fun onCreateScreen(intent: Intent): Screen { + return HelloWorldScreen(carContext) + } + } + } + + override fun createHostValidator(): HostValidator { + return if ((applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0) { + HostValidator.ALLOW_ALL_HOSTS_VALIDATOR + } else { + HostValidator.Builder(applicationContext) + .addAllowedHosts(R.array.hosts_allowlist_sample) + .build() + } + } +} diff --git a/car_app_library/helloworld/common/src/main/res/drawable/ic_launcher.xml b/car_app_library/helloworld/shared/src/main/res/drawable/ic_launcher.xml similarity index 100% rename from car_app_library/helloworld/common/src/main/res/drawable/ic_launcher.xml rename to car_app_library/helloworld/shared/src/main/res/drawable/ic_launcher.xml diff --git a/car_app_library/helloworld/common/src/main/res/values/strings.xml b/car_app_library/helloworld/shared/src/main/res/values/strings.xml similarity index 100% rename from car_app_library/helloworld/common/src/main/res/values/strings.xml rename to car_app_library/helloworld/shared/src/main/res/values/strings.xml diff --git a/car_app_library/helloworld/common/src/main/res/xml/automotive_app_desc.xml b/car_app_library/helloworld/shared/src/main/res/xml/automotive_app_desc.xml similarity index 100% rename from car_app_library/helloworld/common/src/main/res/xml/automotive_app_desc.xml rename to car_app_library/helloworld/shared/src/main/res/xml/automotive_app_desc.xml diff --git a/car_app_library/helloworld/shared/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldScreenTest.kt b/car_app_library/helloworld/shared/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldScreenTest.kt new file mode 100644 index 0000000..e69de29 diff --git a/car_app_library/helloworld/shared/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldSessionTest.kt b/car_app_library/helloworld/shared/src/test/java/androidx/car/app/sample/helloworld/common/HelloWorldSessionTest.kt new file mode 100644 index 0000000..e69de29 diff --git a/car_app_library/helloworld/common/src/test/resources/robolectric.properties b/car_app_library/helloworld/shared/src/test/resources/robolectric.properties similarity index 100% rename from car_app_library/helloworld/common/src/test/resources/robolectric.properties rename to car_app_library/helloworld/shared/src/test/resources/robolectric.properties diff --git a/car_app_library/navigation/automotive/.gitignore b/car_app_library/navigation/automotive/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/navigation/automotive/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/navigation/automotive/build.gradle b/car_app_library/navigation/automotive/build.gradle deleted file mode 100644 index 4073af5..0000000 --- a/car_app_library/navigation/automotive/build.gradle +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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. - */ - -apply plugin: 'com.android.application' - -android { - compileSdk 33 - - defaultConfig { - applicationId "androidx.car.app.sample.navigation" - minSdkVersion 29 - targetSdkVersion 33 - // Increment this to generate signed builds for uploading to Playstore - // Make sure this is different from the navigation-mobile version - versionCode 113 - versionName "113" - } - - buildTypes { - release { - // Enables code shrinking, obfuscation, and optimization. - minifyEnabled true - proguardFiles getDefaultProguardFile( - 'proguard-android-optimize.txt'), - 'proguard-rules.pro' - } - } - - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.navigation" -} - -dependencies { - implementation "androidx.car.app:app-automotive:1.3.0-beta01" - implementation project(":navigation:common") -} diff --git a/car_app_library/navigation/automotive/build.gradle.kts b/car_app_library/navigation/automotive/build.gradle.kts new file mode 100644 index 0000000..d222dde --- /dev/null +++ b/car_app_library/navigation/automotive/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + kotlin("android") + id("android-application-module") +} + +android { + namespace = "androidx.car.app.sample.navigation" + defaultConfig { + applicationId = "androidx.car.app.sample.navigation" + } +} + +dependencies { + implementation(libs.androidx.car.automotive) +// implementation(libs.androidx.core.ktx) +// implementation(libs.androidx.appcompat) + implementation(project(":car_app_library:navigation:shared")) +// testImplementation(libs.junit) +// androidTestImplementation(libs.androidx.junit) +// androidTestImplementation(libs.androidx.espresso.core) +} \ No newline at end of file diff --git a/car_app_library/navigation/common/build.gradle b/car_app_library/navigation/common/build.gradle deleted file mode 100644 index a757539..0000000 --- a/car_app_library/navigation/common/build.gradle +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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. - */ - -apply plugin: 'com.android.library' - -android { - compileSdk 33 - - defaultConfig { - minSdkVersion 23 - targetSdkVersion 33 - versionCode 1 - versionName "1.0" - } - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.navigation.common" -} - -dependencies { - implementation "androidx.constraintlayout:constraintlayout:1.1.3" - implementation "androidx.core:core:1.5.0-alpha01" - - implementation "androidx.car.app:app:1.3.0-beta01" - implementation "androidx.annotation:annotation-experimental:1.0.0" -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.java deleted file mode 100644 index 25ed4cd..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.app; - -import android.Manifest; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.Bundle; -import android.os.IBinder; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.Toast; - -import androidx.activity.ComponentActivity; -import androidx.annotation.Nullable; -import androidx.car.app.connection.CarConnection; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.sample.navigation.common.nav.NavigationService; - -/** - * The main app activity. - * - *

See {@link androidx.car.app.sample.navigation.common.car.NavigationCarAppService} for the - * app's entry point to the cat host. - */ -public class MainActivity extends ComponentActivity { - static final String TAG = MainActivity.class.getSimpleName(); - - // A reference to the navigation service used to get location updates and routing. - NavigationService mService = null; - - // Tracks the bound state of the navigation service. - boolean mIsBound = false; - - // Monitors the state of the connection to the navigation service. - private final ServiceConnection mServiceConnection = - new ServiceConnection() { - - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - Log.i(TAG, "In onServiceConnected() component:" + name); - NavigationService.LocalBinder binder = (NavigationService.LocalBinder) service; - mService = binder.getService(); - mIsBound = true; - } - - @Override - public void onServiceDisconnected(ComponentName name) { - Log.i(TAG, "In onServiceDisconnected() component:" + name); - mService = null; - mIsBound = false; - } - }; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Log.i(TAG, "In onCreate()"); - - setContentView(R.layout.activity_main); - - // Hook up some manual navigation controls. - Button startNavButton = findViewById(R.id.start_nav); - startNavButton.setOnClickListener(this::startNavigation); - Button stopNavButton = findViewById(R.id.stop_nav); - stopNavButton.setOnClickListener(this::stopNavigation); - - new CarConnection(this).getType().observe(this, - this::onConnectionStateUpdate); - } - - @Override - protected void onStart() { - super.onStart(); - Log.i(TAG, "In onStart()"); - bindService( - new Intent(this, NavigationService.class), - mServiceConnection, - Context.BIND_AUTO_CREATE); - requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); - } - - @Override - protected void onStop() { - Log.i(TAG, "In onStop(). bound" + mIsBound); - if (mIsBound) { - // Unbind from the service. This signals to the service that this activity is no longer - // in the foreground, and the service can respond by promoting itself to a foreground - // service. - unbindService(mServiceConnection); - mIsBound = false; - mService = null; - } - super.onStop(); - } - - private void onConnectionStateUpdate(Integer connectionState) { - String message = connectionState > CarConnection.CONNECTION_TYPE_NOT_CONNECTED - ? "Connected to a car head unit" - : "Not Connected to a car head unit"; - Toast.makeText(this, message, Toast.LENGTH_LONG).show(); - } - - private void startNavigation(View view) { - if (mService != null) { - mService.startNavigation(); - } - } - - private void stopNavigation(View view) { - if (mService != null) { - mService.stopNavigation(); - } - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/FavoritesScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/FavoritesScreen.java deleted file mode 100644 index df03872..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/FavoritesScreen.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import static android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE; - -import android.text.SpannableString; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ActionStrip; -import androidx.car.app.model.CarLocation; -import androidx.car.app.model.Distance; -import androidx.car.app.model.DistanceSpan; -import androidx.car.app.model.Header; -import androidx.car.app.model.ItemList; -import androidx.car.app.model.Metadata; -import androidx.car.app.model.Place; -import androidx.car.app.model.Row; -import androidx.car.app.model.Template; -import androidx.car.app.navigation.model.PlaceListNavigationTemplate; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.sample.navigation.common.model.DemoScripts; -import androidx.car.app.sample.navigation.common.model.PlaceInfo; - -import java.util.ArrayList; -import java.util.List; - -/** Screen for showing a list of favorite places. */ -public final class FavoritesScreen extends Screen { - private static final String TAG = "NavigationDemo"; - - @Nullable - private List mFavorites; - @NonNull - private final Action mSettingsAction; - @NonNull - private final SurfaceRenderer mSurfaceRenderer; - - public FavoritesScreen( - @NonNull CarContext carContext, - @NonNull Action settingsAction, - @NonNull SurfaceRenderer surfaceRenderer) { - super(carContext); - mSettingsAction = settingsAction; - mSurfaceRenderer = surfaceRenderer; - } - - @NonNull - @Override - public Template onGetTemplate() { - Log.i(TAG, "In FavoritesScreen.onGetTemplate()"); - mSurfaceRenderer.updateMarkerVisibility( - /* showMarkers=*/ false, /* numMarkers=*/ 0, /* activeMarker=*/ -1); - ItemList.Builder listBuilder = new ItemList.Builder(); - - for (PlaceInfo place : getFavorites()) { - SpannableString address = new SpannableString(" \u00b7 " + place.getDisplayAddress()); - DistanceSpan distanceSpan = - DistanceSpan.create( - Distance.create(/* displayDistance= */ 1, Distance.UNIT_KILOMETERS_P1)); - address.setSpan(distanceSpan, 0, 1, SPAN_INCLUSIVE_INCLUSIVE); - listBuilder.addItem( - new Row.Builder() - .setTitle(place.getName()) - .addText(address) - .setOnClickListener(() -> onClickFavorite()) - .setMetadata( - new Metadata.Builder() - .setPlace( - new Place.Builder(CarLocation.create(1, 1)) - .build()) - .build()) - .build()); - } - - Header header = new Header.Builder() - .setStartHeaderAction(Action.BACK) - .setTitle(getCarContext().getString(R.string.app_name)) - .build(); - - return new PlaceListNavigationTemplate.Builder() - .setItemList(listBuilder.build()) - .setActionStrip(new ActionStrip.Builder().addAction(mSettingsAction).build()) - .setHeader(header) - .build(); - } - - private void onClickFavorite() { - getScreenManager() - .pushForResult( - new RoutePreviewScreen(getCarContext(), mSettingsAction, mSurfaceRenderer), - this::onRoutePreviewResult); - } - - private void onRoutePreviewResult(@Nullable Object previewResult) { - int previewIndex = previewResult == null ? -1 : (int) previewResult; - if (previewIndex < 0) { - return; - } - // Start the same demo instructions. More will be added in the future. - setResult(DemoScripts.getNavigateHome(getCarContext())); - finish(); - } - - @NonNull - private List getFavorites() { - // Lazy initialize mFavorites. - if (mFavorites != null) { - return mFavorites; - } - ArrayList favorites = new ArrayList<>(); - PlaceInfo home = - new PlaceInfo( - getCarContext().getString(R.string.home_destination_label), - "9 10th Street."); - favorites.add(home); - PlaceInfo work = - new PlaceInfo( - getCarContext().getString(R.string.work_destination_label), - "2 3rd Street."); - favorites.add(work); - mFavorites = favorites; - return mFavorites; - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/MicrophoneRecorder.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/MicrophoneRecorder.java deleted file mode 100644 index 8734b4f..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/MicrophoneRecorder.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2022 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import static android.Manifest.permission.RECORD_AUDIO; -import static android.media.AudioAttributes.CONTENT_TYPE_MUSIC; -import static android.media.AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE; -import static android.media.AudioFormat.CHANNEL_OUT_MONO; -import static android.media.AudioFormat.ENCODING_DEFAULT; -import static android.media.AudioManager.AUDIOFOCUS_REQUEST_GRANTED; -import static android.os.Build.VERSION.SDK_INT; - -import static androidx.car.app.media.CarAudioRecord.AUDIO_CONTENT_BUFFER_SIZE; -import static androidx.car.app.media.CarAudioRecord.AUDIO_CONTENT_SAMPLING_RATE; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.pm.PackageManager; -import android.media.AudioAttributes; -import android.media.AudioFocusRequest; -import android.media.AudioFormat; -import android.media.AudioManager; -import android.media.AudioTrack; -import android.os.Build.VERSION_CODES; - -import androidx.annotation.NonNull; -import androidx.annotation.RequiresPermission; -import androidx.car.app.CarContext; -import androidx.car.app.CarToast; -import androidx.car.app.media.CarAudioRecord; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** Manages recording the microphone and accessing the stored data from the microphone. */ -public class MicrophoneRecorder { - private static final String FILE_NAME = "recording.wav"; - - private final CarContext mCarContext; - - public MicrophoneRecorder(@NonNull CarContext carContext) { - mCarContext = carContext; - } - - /** - * Starts recording the car microphone, then plays it back. - */ - public void record() { - if (mCarContext.checkSelfPermission(RECORD_AUDIO) - != PackageManager.PERMISSION_GRANTED) { - CarToast.makeText(mCarContext, "Grant mic permission on phone", - CarToast.LENGTH_LONG).show(); - List permissions = Collections.singletonList(RECORD_AUDIO); - mCarContext.requestPermissions(permissions, (grantedPermissions, - rejectedPermissions) -> { - if (grantedPermissions.contains(RECORD_AUDIO)) { - record(); - } - }); - return; - } - CarAudioRecord record = CarAudioRecord.create(mCarContext); - - Thread recordingThread = - new Thread( - () -> doRecord(record), - "AudioRecorder Thread"); - recordingThread.start(); - } - - @SuppressLint("ClassVerificationFailure") // runtime check for < API 26 - @RequiresPermission(RECORD_AUDIO) - private void play(AudioFocusRequest audioFocusRequest) { - if (SDK_INT < VERSION_CODES.O) { - return; - } - - InputStream inputStream; - try { - inputStream = mCarContext.openFileInput(FILE_NAME); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return; - } - - AudioTrack audioTrack = new AudioTrack.Builder() - .setAudioAttributes(new AudioAttributes.Builder() - .setUsage(USAGE_ASSISTANCE_NAVIGATION_GUIDANCE) - .setContentType(CONTENT_TYPE_MUSIC) - .build()) - .setAudioFormat(new AudioFormat.Builder() - .setEncoding(ENCODING_DEFAULT) - .setSampleRate(AUDIO_CONTENT_SAMPLING_RATE) - .setChannelMask(CHANNEL_OUT_MONO) - .build()) - .setBufferSizeInBytes(AUDIO_CONTENT_BUFFER_SIZE) - .build(); - audioTrack.play(); - try { - while (inputStream.available() > 0) { - byte[] audioData = new byte[AUDIO_CONTENT_BUFFER_SIZE]; - int size = inputStream.read(audioData, 0, audioData.length); - - if (size < 0) { - // End of file - return; - } - audioTrack.write(audioData, 0, size); - } - } catch (IOException e) { - throw new IllegalStateException(e); - } - audioTrack.stop(); - // Abandon the FocusRequest so that user's media can be resumed - mCarContext.getSystemService(AudioManager.class).abandonAudioFocusRequest( - audioFocusRequest); - } - - @SuppressLint("ClassVerificationFailure") // runtime check for < API 26 - @RequiresPermission(RECORD_AUDIO) - private void doRecord(CarAudioRecord record) { - if (SDK_INT < VERSION_CODES.O) { - return; - } - - // Take audio focus so that user's media is not recorded - AudioAttributes audioAttributes = - new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) - .setUsage(USAGE_ASSISTANCE_NAVIGATION_GUIDANCE) - .build(); - - AudioFocusRequest audioFocusRequest = - new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE) - .setAudioAttributes(audioAttributes) - .setOnAudioFocusChangeListener(state -> { - if (state == AudioManager.AUDIOFOCUS_LOSS) { - // Stop recording if audio focus is lost - record.stopRecording(); - } - }) - .build(); - - if (mCarContext.getSystemService(AudioManager.class).requestAudioFocus(audioFocusRequest) - != AUDIOFOCUS_REQUEST_GRANTED) { - return; - } - - record.startRecording(); - - List bytes = new ArrayList<>(); - boolean isRecording = true; - while (isRecording) { - // gets the voice output from microphone to byte format - byte[] bData = new byte[AUDIO_CONTENT_BUFFER_SIZE]; - int len = record.read(bData, 0, AUDIO_CONTENT_BUFFER_SIZE); - - if (len > 0) { - for (int i = 0; i < len; i++) { - bytes.add(bData[i]); - } - } else { - isRecording = false; - } - } - - try { - OutputStream outputStream = mCarContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE); - addHeader(outputStream, bytes.size()); - for (Byte b : bytes) { - outputStream.write(b); - } - - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - record.stopRecording(); - play(audioFocusRequest); - } - - private void addHeader(OutputStream outputStream, int totalAudioLen) throws IOException { - int totalDataLen = totalAudioLen + 36; - byte[] header = new byte[44]; - int dataElementSize = 8; - long longSampleRate = AUDIO_CONTENT_SAMPLING_RATE; - - // See http://soundfile.sapp.org/doc/WaveFormat/ - header[0] = 'R'; // RIFF/WAVE header - header[1] = 'I'; - header[2] = 'F'; - header[3] = 'F'; - header[4] = (byte) (totalAudioLen & 0xff); - header[5] = (byte) ((totalDataLen >> 8) & 0xff); - header[6] = (byte) ((totalDataLen >> 16) & 0xff); - header[7] = (byte) ((totalDataLen >> 24) & 0xff); - header[8] = 'W'; - header[9] = 'A'; - header[10] = 'V'; - header[11] = 'E'; - header[12] = 'f'; // 'fmt ' chunk - header[13] = 'm'; - header[14] = 't'; - header[15] = ' '; - header[16] = 16; // 4 bytes: size of 'fmt ' chunk - header[17] = 0; - header[18] = 0; - header[19] = 0; - header[20] = 1; // format = 1 PCM - header[21] = 0; - header[22] = 1; // Num channels (mono) - header[23] = 0; - header[24] = (byte) (longSampleRate & 0xff); // sample rate - header[25] = (byte) ((longSampleRate >> 8) & 0xff); - header[26] = (byte) ((longSampleRate >> 16) & 0xff); - header[27] = (byte) ((longSampleRate >> 24) & 0xff); - header[28] = (byte) (longSampleRate & 0xff); // byte rate - header[29] = (byte) ((longSampleRate >> 8) & 0xff); - header[30] = (byte) ((longSampleRate >> 16) & 0xff); - header[31] = (byte) ((longSampleRate >> 24) & 0xff); - header[32] = 1; // block align - header[33] = 0; - header[34] = (byte) (dataElementSize & 0xff); // bits per sample - header[35] = (byte) ((dataElementSize >> 8) & 0xff); - header[36] = 'd'; - header[37] = 'a'; - header[38] = 't'; - header[39] = 'a'; - header[40] = (byte) (totalAudioLen & 0xff); - header[41] = (byte) ((totalAudioLen >> 8) & 0xff); - header[42] = (byte) ((totalAudioLen >> 16) & 0xff); - header[43] = (byte) ((totalAudioLen >> 24) & 0xff); - - outputStream.write(header, 0, 44); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationCarAppService.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationCarAppService.java deleted file mode 100644 index 84dcbfe..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationCarAppService.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.content.pm.ApplicationInfo; -import android.net.Uri; -import android.os.Build; - -import androidx.annotation.NonNull; -import androidx.car.app.CarAppService; -import androidx.car.app.Session; -import androidx.car.app.SessionInfo; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.validation.HostValidator; -import androidx.core.app.NotificationCompat; -import androidx.lifecycle.DefaultLifecycleObserver; -import androidx.lifecycle.LifecycleOwner; - -/** - * Entry point for the templated app. - * - *

{@link CarAppService} is the main interface between the app and the car host. For more - * details, see the Android for - * Cars Library developer guide. - */ -public final class NavigationCarAppService extends CarAppService { - /** Navigation session channel id. */ - public static final String CHANNEL_ID = "NavigationSessionChannel"; - - /** The identifier for the notification displayed for the foreground service. */ - private static final int NOTIFICATION_ID = 97654321; - - /** Create a deep link URL from the given deep link action. */ - @NonNull - public static Uri createDeepLinkUri(@NonNull String deepLinkAction) { - return Uri.fromParts( - NavigationSession.URI_SCHEME, NavigationSession.URI_HOST, deepLinkAction); - } - - @SuppressWarnings("deprecation") - @Override - @NonNull - public Session onCreateSession(@NonNull SessionInfo sessionInfo) { - createNotificationChannel(); - - // Turn the car app service into a foreground service in order to make sure we can use all - // granted "while-in-use" permissions (e.g. location) in the app's process. - // The "while-in-use" location permission is granted as long as there is a foreground - // service running in a process in which location access takes place. Here, we set this - // service, and not NavigationService (which runs only during navigation), as a - // foreground service because we need location access even when not navigating. If - // location access is needed only during navigation, we can set NavigationService as a - // foreground service instead. - // See https://developer.android.com/reference/com/google/android/libraries/car/app - // /CarAppService#accessing-location for more details. - startForeground(NOTIFICATION_ID, getNotification()); - NavigationSession session = new NavigationSession(sessionInfo); - session.getLifecycle() - .addObserver( - new DefaultLifecycleObserver() { - @Override - public void onDestroy(@NonNull LifecycleOwner owner) { - stopForeground(true); - } - }); - - return session; - } - - @NonNull - @Override - public HostValidator createHostValidator() { - if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { - return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR; - } else { - return new HostValidator.Builder(getApplicationContext()) - .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample) - .build(); - } - } - - private void createNotificationChannel() { - NotificationManager notificationManager = getSystemService(NotificationManager.class); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - CharSequence name = "Car App Service"; - NotificationChannel serviceChannel = - new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH); - notificationManager.createNotificationChannel(serviceChannel); - } - } - - /** Returns the {@link NotificationCompat} used as part of the foreground service. */ - private Notification getNotification() { - NotificationCompat.Builder builder = - new NotificationCompat.Builder(this, CHANNEL_ID) - .setContentTitle("Navigation App") - .setContentText("App is running") - .setSmallIcon(R.drawable.ic_launcher); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - builder.setChannelId(CHANNEL_ID); - builder.setPriority(NotificationManager.IMPORTANCE_HIGH); - } - return builder.build(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationScreen.java deleted file mode 100644 index 3d72083..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationScreen.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.CarToast; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ActionStrip; -import androidx.car.app.model.CarColor; -import androidx.car.app.model.CarIcon; -import androidx.car.app.model.Distance; -import androidx.car.app.model.Template; -import androidx.car.app.navigation.model.Destination; -import androidx.car.app.navigation.model.Lane; -import androidx.car.app.navigation.model.MessageInfo; -import androidx.car.app.navigation.model.NavigationTemplate; -import androidx.car.app.navigation.model.RoutingInfo; -import androidx.car.app.navigation.model.Step; -import androidx.car.app.navigation.model.TravelEstimate; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.sample.navigation.common.model.Instruction; -import androidx.core.graphics.drawable.IconCompat; - -import java.util.ArrayList; -import java.util.List; - -/** Simple demo of how to present a trip on the routing screen. */ -public final class NavigationScreen extends Screen { - /** Invalid zoom focal point value, used for the zoom buttons. */ - private static final float INVALID_FOCAL_POINT_VAL = -1f; - - /** Zoom-in scale factor, used for the zoom-in button. */ - private static final float ZOOM_IN_BUTTON_SCALE_FACTOR = 1.1f; - - /** Zoom-out scale factor, used for the zoom-out button. */ - private static final float ZOOM_OUT_BUTTON_SCALE_FACTOR = 0.9f; - - /** A listener for navigation start and stop signals. */ - public interface Listener { - /** Executes the given instructions. */ - void executeScript(@NonNull List instructions); - - /** Stops navigation. */ - void stopNavigation(); - } - - @NonNull - private final Listener mListener; - @NonNull - private final Action mSettingsAction; - @NonNull - private final SurfaceRenderer mSurfaceRenderer; - @NonNull - private final MicrophoneRecorder mMicrophoneRecorder; - - private boolean mIsNavigating; - private boolean mIsRerouting; - private boolean mHasArrived; - - @Nullable - private List mDestinations; - - @Nullable - private List mSteps; - - @Nullable - private Distance mStepRemainingDistance; - - @Nullable - private TravelEstimate mDestinationTravelEstimate; - private boolean mShouldShowNextStep; - private boolean mShouldShowLanes; - - @Nullable - CarIcon mJunctionImage; - - private boolean mIsInPanMode; - - public NavigationScreen( - @NonNull CarContext carContext, - @NonNull Action settingsAction, - @NonNull Listener listener, - @NonNull SurfaceRenderer surfaceRenderer) { - super(carContext); - mListener = listener; - mSettingsAction = settingsAction; - mSurfaceRenderer = surfaceRenderer; - mMicrophoneRecorder = new MicrophoneRecorder(carContext); - } - - /** Updates the navigation screen with the next instruction. */ - public void updateTrip( - boolean isNavigating, - boolean isRerouting, - boolean hasArrived, - @Nullable List destinations, - @Nullable List steps, - @Nullable TravelEstimate nextDestinationTravelEstimate, - @Nullable Distance nextStepRemainingDistance, - boolean shouldShowNextStep, - boolean shouldShowLanes, - @Nullable CarIcon junctionImage) { - mIsNavigating = isNavigating; - mIsRerouting = isRerouting; - mHasArrived = hasArrived; - mDestinations = destinations; - mSteps = steps; - mStepRemainingDistance = nextStepRemainingDistance; - mDestinationTravelEstimate = nextDestinationTravelEstimate; - mShouldShowNextStep = shouldShowNextStep; - mShouldShowLanes = shouldShowLanes; - mJunctionImage = junctionImage; - invalidate(); - } - - @NonNull - @Override - public Template onGetTemplate() { - mSurfaceRenderer.updateMarkerVisibility( - /* showMarkers=*/ false, /* numMarkers=*/ 0, /* activeMarker=*/ -1); - - NavigationTemplate.Builder builder = new NavigationTemplate.Builder(); - builder.setBackgroundColor(CarColor.SECONDARY); - - // Set the action strip. - ActionStrip.Builder actionStripBuilder = new ActionStrip.Builder(); - if (mIsNavigating) { - actionStripBuilder.addAction( - new Action.Builder() - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_add_stop)) - .build()) - .setOnClickListener(this::openFavorites) - .build()); - } - - actionStripBuilder.addAction(mSettingsAction); - actionStripBuilder.addAction( - new Action.Builder() - .setTitle("Voice") - .setIcon(new CarIcon.Builder( - IconCompat.createWithResource(getCarContext(), - R.drawable.ic_mic)).build()).setOnClickListener( - mMicrophoneRecorder::record) - .build()); - if (mIsNavigating) { - actionStripBuilder.addAction( - new Action.Builder() - .setTitle("Stop") - .setOnClickListener(this::stopNavigation) - .build()); - } else { - actionStripBuilder.addAction( - new Action.Builder() - .setTitle("Search") - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_search_black36dp)) - .build()) - .setOnClickListener(this::openSearch) - .build()); - actionStripBuilder.addAction( - new Action.Builder() - .setTitle("Favorites") - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_favorite_white_24dp)) - .build()) - .setOnClickListener(this::openFavorites) - .build()); - } - builder.setActionStrip(actionStripBuilder.build()); - - // Set the map action strip with the pan and zoom buttons. - CarIcon.Builder panIconBuilder = new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_pan_24)); - if (mIsInPanMode) { - panIconBuilder.setTint(CarColor.BLUE); - } - - builder.setMapActionStrip(new ActionStrip.Builder() - .addAction(new Action.Builder(Action.PAN) - .setIcon(panIconBuilder.build()) - .build()) - .addAction( - new Action.Builder() - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_recenter_24)) - .build()) - .setOnClickListener( - () -> mSurfaceRenderer.handleRecenter()) - .build()) - .addAction( - new Action.Builder() - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_zoom_out_24)) - .build()) - .setOnClickListener( - () -> mSurfaceRenderer.handleScale(INVALID_FOCAL_POINT_VAL, - INVALID_FOCAL_POINT_VAL, - ZOOM_OUT_BUTTON_SCALE_FACTOR)) - .build()) - .addAction( - new Action.Builder() - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), - R.drawable.ic_zoom_in_24)) - .build()) - .setOnClickListener( - () -> mSurfaceRenderer.handleScale(INVALID_FOCAL_POINT_VAL, - INVALID_FOCAL_POINT_VAL, - ZOOM_IN_BUTTON_SCALE_FACTOR)) - .build()) - .build()); - - // When the user enters the pan mode, remind the user that they can exit the pan mode by - // pressing the select button again. - builder.setPanModeListener(isInPanMode -> { - if (isInPanMode) { - CarToast.makeText(getCarContext(), - "Press Select to exit the pan mode", - CarToast.LENGTH_LONG).show(); - } - mIsInPanMode = isInPanMode; - invalidate(); - }); - - if (mIsNavigating) { - if (mDestinationTravelEstimate != null) { - builder.setDestinationTravelEstimate(mDestinationTravelEstimate); - } - - if (isRerouting()) { - builder.setNavigationInfo(new RoutingInfo.Builder().setLoading(true).build()); - } else if (mHasArrived) { - - MessageInfo messageInfo = new MessageInfo.Builder( - getCarContext().getString(R.string.navigation_arrived)).build(); - builder.setNavigationInfo(messageInfo); - } else { - RoutingInfo.Builder info = new RoutingInfo.Builder(); - Step tmp = mSteps.get(0); - Step.Builder currentStep = - new Step.Builder(tmp.getCue().toCharSequence()) - .setManeuver(tmp.getManeuver()) - .setRoad(tmp.getRoad().toCharSequence()); - if (mShouldShowLanes) { - for (Lane lane : tmp.getLanes()) { - currentStep.addLane(lane); - } - currentStep.setLanesImage(tmp.getLanesImage()); - } - info.setCurrentStep(currentStep.build(), mStepRemainingDistance); - if (mShouldShowNextStep && mSteps.size() > 1) { - info.setNextStep(mSteps.get(1)); - } - if (mJunctionImage != null) { - info.setJunctionImage(mJunctionImage); - } - builder.setNavigationInfo(info.build()); - } - } - - return builder.build(); - } - - private boolean isRerouting() { - return mIsRerouting || mDestinations == null; - } - - private void stopNavigation() { - mListener.stopNavigation(); - } - - private void openFavorites() { - getScreenManager() - .pushForResult( - new FavoritesScreen(getCarContext(), mSettingsAction, mSurfaceRenderer), - (obj) -> { - if (obj == null || mIsNavigating) { - return; - } - // Need to copy over each element to satisfy Java type safety. - List results = (List) obj; - List instructions = new ArrayList(); - for (Object result : results) { - instructions.add((Instruction) result); - } - mListener.executeScript(instructions); - }); - } - - private void openSearch() { - getScreenManager() - .pushForResult( - new SearchScreen(getCarContext(), mSettingsAction, mSurfaceRenderer), - (obj) -> { - if (obj != null) { - // Need to copy over each element to satisfy Java type safety. - List results = (List) obj; - List instructions = new ArrayList(); - for (Object result : results) { - instructions.add((Instruction) result); - } - mListener.executeScript(instructions); - } - }); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationSession.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationSession.java deleted file mode 100644 index 4fe2428..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/NavigationSession.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import android.Manifest; -import android.annotation.SuppressLint; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.content.pm.PackageManager; -import android.content.res.Configuration; -import android.location.Location; -import android.location.LocationManager; -import android.net.Uri; -import android.os.IBinder; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.CarToast; -import androidx.car.app.Screen; -import androidx.car.app.ScreenManager; -import androidx.car.app.Session; -import androidx.car.app.SessionInfo; -import androidx.car.app.model.Action; -import androidx.car.app.model.CarIcon; -import androidx.car.app.model.Distance; -import androidx.car.app.navigation.model.Destination; -import androidx.car.app.navigation.model.Step; -import androidx.car.app.navigation.model.TravelEstimate; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.sample.navigation.common.model.Instruction; -import androidx.car.app.sample.navigation.common.nav.NavigationService; -import androidx.core.graphics.drawable.IconCompat; -import androidx.core.location.LocationListenerCompat; -import androidx.lifecycle.DefaultLifecycleObserver; -import androidx.lifecycle.Lifecycle; -import androidx.lifecycle.LifecycleObserver; -import androidx.lifecycle.LifecycleOwner; - -import java.util.ArrayList; -import java.util.List; - -/** Session class for the Navigation sample app. */ -class NavigationSession extends Session implements NavigationScreen.Listener { - static final String TAG = NavigationSession.class.getSimpleName(); - - static final String URI_SCHEME = "samples"; - static final String URI_HOST = "navigation"; - - @Nullable - NavigationScreen mNavigationScreen; - - @Nullable - SurfaceRenderer mNavigationCarSurface; - - // A reference to the navigation service used to get location updates and routing. - @Nullable - NavigationService mService; - - @NonNull - Action mSettingsAction; - - final NavigationService.Listener mServiceListener = - new NavigationService.Listener() { - @Override - public void navigationStateChanged( - boolean isNavigating, - boolean isRerouting, - boolean hasArrived, - @Nullable List destinations, - @Nullable List steps, - @Nullable TravelEstimate nextDestinationTravelEstimate, - @Nullable Distance nextStepRemainingDistance, - boolean shouldShowNextStep, - boolean shouldShowLanes, - @Nullable CarIcon junctionImage) { - mNavigationScreen.updateTrip( - isNavigating, - isRerouting, - hasArrived, - destinations, - steps, - nextDestinationTravelEstimate, - nextStepRemainingDistance, - shouldShowNextStep, - shouldShowLanes, - junctionImage); - } - }; - - // A listener to periodically update the surface with the location coordinates - LocationListenerCompat mLocationListener = - location -> mNavigationCarSurface.updateLocationString(getLocationString(location)); - - // Monitors the state of the connection to the Navigation service. - final ServiceConnection mServiceConnection = - new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - Log.i(TAG, "In onServiceConnected() component:" + name); - NavigationService.LocalBinder binder = (NavigationService.LocalBinder) service; - mService = binder.getService(); - mService.setCarContext(getCarContext(), mServiceListener); - } - - @Override - public void onServiceDisconnected(ComponentName name) { - Log.i(TAG, "In onServiceDisconnected() component:" + name); - // Unhook map models here - mService.clearCarContext(); - mService = null; - } - }; - - private final LifecycleObserver mLifeCycleObserver = - new DefaultLifecycleObserver() { - - @Override - public void onCreate(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onCreate()"); - } - - @Override - public void onStart(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onStart()"); - getCarContext() - .bindService( - new Intent(getCarContext(), NavigationService.class), - mServiceConnection, - Context.BIND_AUTO_CREATE); - } - - @Override - public void onResume(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onResume()"); - } - - @Override - public void onPause(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onPause()"); - } - - @Override - public void onStop(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onStop()"); - getCarContext().unbindService(mServiceConnection); - mService = null; - } - - @Override - public void onDestroy(@NonNull LifecycleOwner lifecycleOwner) { - Log.i(TAG, "In onDestroy()"); - - LocationManager locationManager = - (LocationManager) - getCarContext().getSystemService(Context.LOCATION_SERVICE); - locationManager.removeUpdates(mLocationListener); - } - }; - - NavigationSession(@NonNull SessionInfo sessionInfo) { - if (sessionInfo.getDisplayType() == SessionInfo.DISPLAY_TYPE_MAIN) { - Lifecycle lifecycle = getLifecycle(); - lifecycle.addObserver(mLifeCycleObserver); - } - } - - @Override - @NonNull - public Screen onCreateScreen(@NonNull Intent intent) { - Log.i(TAG, "In onCreateScreen()"); - - mSettingsAction = - new Action.Builder() - .setIcon( - new CarIcon.Builder( - IconCompat.createWithResource( - getCarContext(), R.drawable.ic_settings)) - .build()) - .setOnClickListener( - () -> { - getCarContext() - .getCarService(ScreenManager.class) - .push(new SettingsScreen(getCarContext())); - }) - .build(); - - mNavigationCarSurface = new SurfaceRenderer(getCarContext(), getLifecycle()); - mNavigationScreen = - new NavigationScreen(getCarContext(), mSettingsAction, this, mNavigationCarSurface); - - String action = intent.getAction(); - if (action != null && CarContext.ACTION_NAVIGATE.equals(action)) { - CarToast.makeText( - getCarContext(), - "Navigation intent: " + intent.getDataString(), - CarToast.LENGTH_LONG) - .show(); - } - - if (getCarContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) - == PackageManager.PERMISSION_GRANTED) { - requestLocationUpdates(); - } else { - // If we do not have the location permission, preseed the navigation screen first, and - // push - // the request permission screen. When the user grants the location permission, the - // request - // permission screen will be popped and the navigation screen will be displayed. - getCarContext().getCarService(ScreenManager.class).push(mNavigationScreen); - return new RequestPermissionScreen(getCarContext(), this::requestLocationUpdates); - } - - return mNavigationScreen; - } - - @Override - public void onNewIntent(@NonNull Intent intent) { - Log.i(TAG, "In onNewIntent() " + intent); - ScreenManager screenManager = getCarContext().getCarService(ScreenManager.class); - if (CarContext.ACTION_NAVIGATE.equals(intent.getAction())) { - Uri uri = Uri.parse("http://" + intent.getDataString()); - screenManager.popToRoot(); - screenManager.pushForResult( - new SearchResultsScreen( - getCarContext(), - mSettingsAction, - mNavigationCarSurface, - uri.getQueryParameter("q")), - (obj) -> { - if (obj != null) { - // Need to copy over each element to satisfy Java type safety. - List results = (List) obj; - List instructions = new ArrayList(); - for (Object result : results) { - instructions.add((Instruction) result); - } - executeScript(instructions); - } - }); - - return; - } - - // Process the intent from DeepLinkNotificationReceiver. Bring the routing screen back to - // the - // top if any other screens were pushed onto it. - Uri uri = intent.getData(); - if (uri != null - && URI_SCHEME.equals(uri.getScheme()) - && URI_HOST.equals(uri.getSchemeSpecificPart())) { - - Screen top = screenManager.getTop(); - switch (uri.getFragment()) { - case NavigationService.DEEP_LINK_ACTION: - if (!(top instanceof NavigationScreen)) { - screenManager.popToRoot(); - } - break; - default: - // No-op - } - } - } - - @Override - public void onCarConfigurationChanged(@NonNull Configuration newConfiguration) { - mNavigationCarSurface.onCarConfigurationChanged(); - } - - @Override - public void executeScript(@NonNull List instructions) { - if (mService != null) { - mService.executeInstructions(instructions); - } - } - - @Override - public void stopNavigation() { - if (mService != null) { - mService.stopNavigation(); - } - } - - /** - * Requests location updates for the navigation surface. - * - * @throws java.lang.SecurityException if the app does not have the location permission. - */ - @SuppressLint("MissingPermission") - void requestLocationUpdates() { - LocationManager locationManager = - (LocationManager) getCarContext().getSystemService(Context.LOCATION_SERVICE); - Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - mNavigationCarSurface.updateLocationString(getLocationString(location)); - locationManager.requestLocationUpdates( - LocationManager.GPS_PROVIDER, - /* minTimeMs= */ 1000, - /* minDistanceM= */ 1, - mLocationListener); - } - - static String getLocationString(@Nullable Location location) { - if (location == null) { - return "unknown"; - } - return "time: " - + location.getTime() - + " lat: " - + location.getLatitude() - + " lng: " - + location.getLongitude(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RequestPermissionScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RequestPermissionScreen.java deleted file mode 100644 index d1400a6..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RequestPermissionScreen.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import static android.Manifest.permission.ACCESS_FINE_LOCATION; - -import androidx.annotation.NonNull; -import androidx.car.app.CarContext; -import androidx.car.app.CarToast; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.CarColor; -import androidx.car.app.model.MessageTemplate; -import androidx.car.app.model.OnClickListener; -import androidx.car.app.model.ParkedOnlyOnClickListener; -import androidx.car.app.model.Template; - -import java.util.ArrayList; -import java.util.List; - -/** Screen for asking the user to grant location permission. */ -public class RequestPermissionScreen extends Screen { - - /** Callback called when the location permission is granted. */ - public interface LocationPermissionCheckCallback { - /** Callback called when the location permission is granted. */ - void onPermissionGranted(); - } - - LocationPermissionCheckCallback mLocationPermissionCheckCallback; - - public RequestPermissionScreen( - @NonNull CarContext carContext, @NonNull LocationPermissionCheckCallback callback) { - super(carContext); - mLocationPermissionCheckCallback = callback; - } - - @NonNull - @Override - public Template onGetTemplate() { - List permissions = new ArrayList<>(); - permissions.add(ACCESS_FINE_LOCATION); - - String message = "This app needs access to location in order to navigate"; - - OnClickListener listener = ParkedOnlyOnClickListener.create(() -> - getCarContext().requestPermissions( - permissions, - (approved, rejected) -> { - CarToast.makeText( - getCarContext(), - String.format("Approved: %s Rejected: %s", approved, rejected), - CarToast.LENGTH_LONG).show(); - if (!approved.isEmpty()) { - mLocationPermissionCheckCallback.onPermissionGranted(); - finish(); - } - })); - - Action action = new Action.Builder() - .setTitle("Grant Access") - .setBackgroundColor(CarColor.GREEN) - .setOnClickListener(listener) - .build(); - - return new MessageTemplate.Builder(message).addAction(action).setHeaderAction( - Action.APP_ICON).build(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RoutePreviewScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RoutePreviewScreen.java deleted file mode 100644 index 2b3bdec..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/RoutePreviewScreen.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import android.text.SpannableString; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ActionStrip; -import androidx.car.app.model.DurationSpan; -import androidx.car.app.model.Header; -import androidx.car.app.model.ItemList; -import androidx.car.app.model.Row; -import androidx.car.app.model.Template; -import androidx.car.app.navigation.model.RoutePreviewNavigationTemplate; -import androidx.car.app.sample.navigation.common.R; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** The route preview screen for the app. */ -public final class RoutePreviewScreen extends Screen { - private static final String TAG = "NavigationDemo"; - - @NonNull - private final Action mSettingsAction; - @NonNull - private final SurfaceRenderer mSurfaceRenderer; - @NonNull - private final List mRouteRows; - - int mLastSelectedIndex = -1; - - public RoutePreviewScreen( - @NonNull CarContext carContext, - @NonNull Action settingsAction, - @NonNull SurfaceRenderer surfaceRenderer) { - super(carContext); - mSettingsAction = settingsAction; - mSurfaceRenderer = surfaceRenderer; - - mRouteRows = new ArrayList<>(); - SpannableString firstRoute = new SpannableString(" \u00b7 Shortest route"); - firstRoute.setSpan(DurationSpan.create(TimeUnit.HOURS.toSeconds(26)), 0, 1, 0); - SpannableString secondRoute = new SpannableString(" \u00b7 Less busy"); - secondRoute.setSpan(DurationSpan.create(TimeUnit.HOURS.toSeconds(24)), 0, 1, 0); - SpannableString thirdRoute = new SpannableString(" \u00b7 HOV friendly"); - thirdRoute.setSpan(DurationSpan.create(TimeUnit.MINUTES.toSeconds(867)), 0, 1, 0); - - mRouteRows.add(new Row.Builder().setTitle(firstRoute).addText("Via NE 8th Street").build()); - mRouteRows.add(new Row.Builder().setTitle(secondRoute).addText("Via NE 1st Ave").build()); - mRouteRows.add(new Row.Builder().setTitle(thirdRoute).addText("Via NE 4th Street").build()); - } - - @NonNull - @Override - public Template onGetTemplate() { - Log.i(TAG, "In RoutePreviewScreen.onGetTemplate()"); - onRouteSelected(0); - - ItemList.Builder listBuilder = new ItemList.Builder(); - listBuilder - .setOnSelectedListener(this::onRouteSelected) - .setOnItemsVisibilityChangedListener(this::onRoutesVisible); - for (Row row : mRouteRows) { - listBuilder.addItem(row); - } - - Header header = new Header.Builder() - .setStartHeaderAction(Action.BACK) - .setTitle(getCarContext().getString(R.string.route_preview)) - .build(); - - return new RoutePreviewNavigationTemplate.Builder() - .setItemList(listBuilder.build()) - .setActionStrip(new ActionStrip.Builder().addAction(mSettingsAction).build()) - .setHeader(header) - .setNavigateAction( - new Action.Builder() - .setTitle("Continue to route") - .setOnClickListener(this::onNavigate) - .build()) - .build(); - } - - private void onRouteSelected(int index) { - mLastSelectedIndex = index; - mSurfaceRenderer.updateMarkerVisibility( - /* showMarkers=*/ true, - /* numMarkers=*/ mRouteRows.size(), - /* activeMarker=*/ mLastSelectedIndex); - } - - private void onRoutesVisible(int startIndex, int endIndex) { - if (Log.isLoggable(TAG, Log.INFO)) { - Log.i(TAG, "In RoutePreviewScreen.onRoutesVisible start:" + startIndex + " end:" - + endIndex); - } - } - - private void onNavigate() { - setResult(mLastSelectedIndex); - finish(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchResultsScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchResultsScreen.java deleted file mode 100644 index 8693519..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchResultsScreen.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import static android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE; - -import android.text.SpannableString; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ActionStrip; -import androidx.car.app.model.CarLocation; -import androidx.car.app.model.Distance; -import androidx.car.app.model.DistanceSpan; -import androidx.car.app.model.Header; -import androidx.car.app.model.ItemList; -import androidx.car.app.model.Metadata; -import androidx.car.app.model.Place; -import androidx.car.app.model.Row; -import androidx.car.app.model.Template; -import androidx.car.app.navigation.model.PlaceListNavigationTemplate; -import androidx.car.app.sample.navigation.common.model.DemoScripts; -import androidx.car.app.sample.navigation.common.model.PlaceInfo; - -/** Screen for showing a list of places from a search. */ -public final class SearchResultsScreen extends Screen { - @NonNull - private final Action mSettingsAction; - @NonNull - private final SurfaceRenderer mSurfaceRenderer; - @NonNull - private final String mSearchText; - - public SearchResultsScreen( - @NonNull CarContext carContext, - @NonNull Action settingsAction, - @NonNull SurfaceRenderer surfaceRenderer, - @NonNull String searchText) { - super(carContext); - mSettingsAction = settingsAction; - mSurfaceRenderer = surfaceRenderer; - mSearchText = searchText; - } - - @NonNull - @Override - public Template onGetTemplate() { - mSurfaceRenderer.updateMarkerVisibility( - /* showMarkers=*/ false, /* numMarkers=*/ 0, /* activeMarker=*/ -1); - ItemList.Builder listBuilder = new ItemList.Builder(); - - int numItems = ((int) (Math.random() * 6.0)) + 1; - - for (int i = 0; i < numItems; i++) { - PlaceInfo place = - new PlaceInfo( - String.format("Result %d", i + 1), - String.format("%d Main Street.", (i + 1) * 10)); - - SpannableString address = new SpannableString(" \u00b7 " + place.getDisplayAddress()); - DistanceSpan distanceSpan = - DistanceSpan.create( - Distance.create( - /* displayDistance= */ i + 1, Distance.UNIT_KILOMETERS_P1)); - address.setSpan(distanceSpan, 0, 1, SPAN_INCLUSIVE_INCLUSIVE); - listBuilder.addItem( - new Row.Builder() - .setTitle(place.getName()) - .addText(address) - .setOnClickListener(() -> onClickItem()) - .setMetadata( - new Metadata.Builder() - .setPlace( - new Place.Builder(CarLocation.create(1, 1)) - .build()) - .build()) - .build()); - } - - Header header = new Header.Builder() - .setStartHeaderAction(Action.BACK) - .setTitle("Search: " + mSearchText) - .build(); - - return new PlaceListNavigationTemplate.Builder() - .setItemList(listBuilder.build()) - .setHeader(header) - .setActionStrip(new ActionStrip.Builder().addAction(mSettingsAction).build()) - .build(); - } - - private void onClickItem() { - getScreenManager() - .pushForResult( - new RoutePreviewScreen(getCarContext(), mSettingsAction, mSurfaceRenderer), - this::onRoutePreviewResult); - } - - private void onRoutePreviewResult(@Nullable Object previewResult) { - int previewIndex = previewResult == null ? -1 : (int) previewResult; - if (previewIndex < 0) { - return; - } - // Start the same demo instructions. More will be added in the future. - setResult(DemoScripts.getNavigateHome(getCarContext())); - finish(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchScreen.java deleted file mode 100644 index 72a8f01..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SearchScreen.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ItemList; -import androidx.car.app.model.Row; -import androidx.car.app.model.SearchTemplate; -import androidx.car.app.model.SearchTemplate.SearchCallback; -import androidx.car.app.model.Template; -import androidx.car.app.sample.navigation.common.model.DemoScripts; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** Screen for showing entering a search and showing initial results. */ -public final class SearchScreen extends Screen { - - @NonNull - private final Action mSettingsAction; - - @NonNull - private final SurfaceRenderer mSurfaceRenderer; - - private ItemList mItemList = withNoResults(new ItemList.Builder()).build(); - final List mTitles = new ArrayList<>(); - - @Nullable - private String mSearchText; - private final List mFakeTitles = - new ArrayList<>(Arrays.asList("Starbucks", "Shell", "Costco", "Aldi", "Safeway")); - - public SearchScreen( - @NonNull CarContext carContext, - @NonNull Action settingsAction, - @NonNull SurfaceRenderer surfaceRenderer) { - super(carContext); - mSettingsAction = settingsAction; - mSurfaceRenderer = surfaceRenderer; - } - - @NonNull - @Override - public Template onGetTemplate() { - return new SearchTemplate.Builder( - new SearchCallback() { - @Override - public void onSearchTextChanged(@NonNull String searchText) { - doSearch(searchText); - } - - @Override - public void onSearchSubmitted(@NonNull String searchTerm) { - // When the user presses the search key use the top item in the list - // as the - // result and simulate as if the user had pressed that. - if (mTitles.size() > 0) { - onClickSearch(mTitles.get(0)); - } - } - }) - .setHeaderAction(Action.BACK) - .setShowKeyboardByDefault(false) - .setItemList(mItemList) - .setInitialSearchText(mSearchText == null ? "" : mSearchText) - .build(); - } - - void doSearch(String searchText) { - mSearchText = searchText; - mTitles.clear(); - ItemList.Builder builder = new ItemList.Builder(); - if (searchText.isEmpty()) { - withNoResults(builder); - } else { - // Create some fake data entries. - for (String title : mFakeTitles) { - mTitles.add(title); - builder.addItem( - new Row.Builder() - .setTitle(title) - .setOnClickListener(() -> onClickSearch(title)) - .build()); - } - } - mItemList = builder.build(); - invalidate(); - return; - } - - void onClickSearch(@NonNull String searchText) { - getScreenManager() - .pushForResult( - new RoutePreviewScreen(getCarContext(), mSettingsAction, mSurfaceRenderer), - this::onRouteSelected); - } - - private static ItemList.Builder withNoResults(ItemList.Builder builder) { - return builder.setNoItemsMessage("No Results"); - } - - private void onRouteSelected(@Nullable Object previewResult) { - int previewIndex = previewResult == null ? -1 : (int) previewResult; - if (previewIndex < 0) { - return; - } - // Start the same demo instructions. More will be added in the future. - setResult(DemoScripts.getNavigateHome(getCarContext())); - finish(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SettingsScreen.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SettingsScreen.java deleted file mode 100644 index c673eab..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SettingsScreen.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import android.content.Context; -import android.content.SharedPreferences; - -import androidx.annotation.NonNull; -import androidx.car.app.CarContext; -import androidx.car.app.Screen; -import androidx.car.app.model.Action; -import androidx.car.app.model.ItemList; -import androidx.car.app.model.ListTemplate; -import androidx.car.app.model.Row; -import androidx.car.app.model.SectionedItemList; -import androidx.car.app.model.Template; -import androidx.car.app.model.Toggle; -import androidx.car.app.sample.navigation.common.R; - -/** Settings screen demo. */ -public final class SettingsScreen extends Screen { - - @NonNull - final SharedPreferences mSharedPref; - - SettingsScreen(@NonNull CarContext carContext) { - super(carContext); - mSharedPref = carContext.getSharedPreferences("SETTINGS", Context.MODE_PRIVATE); - } - - @NonNull - @Override - public Template onGetTemplate() { - ListTemplate.Builder templateBuilder = new ListTemplate.Builder(); - - // Create 2 sections with three settings each. - ItemList.Builder sectionABuilder = new ItemList.Builder(); - sectionABuilder.addItem(buildRow(R.string.settings_one_label, R.string.settings_one_pref)); - sectionABuilder.addItem(buildRow(R.string.settings_two_label, R.string.settings_two_pref)); - sectionABuilder.addItem( - buildRow(R.string.settings_three_label, R.string.settings_three_pref)); - - templateBuilder.addSectionedList( - SectionedItemList.create( - sectionABuilder.build(), - getCarContext().getString(R.string.settings_section_a_label))); - - ItemList.Builder sectionBBuilder = new ItemList.Builder(); - sectionBBuilder.addItem( - buildRow(R.string.settings_four_label, R.string.settings_four_pref)); - sectionBBuilder.addItem( - buildRow(R.string.settings_five_label, R.string.settings_five_pref)); - sectionBBuilder.addItem(buildRow(R.string.settings_six_label, R.string.settings_six_pref)); - - templateBuilder.addSectionedList( - SectionedItemList.create( - sectionBBuilder.build(), - getCarContext().getString(R.string.settings_section_b_label))); - return templateBuilder - .setHeaderAction(Action.BACK) - .setTitle(getCarContext().getString(R.string.settings_title)) - .build(); - } - - @NonNull - private Row buildRow(int labelResourcee, int prefKeyResource) { - return new Row.Builder() - .setTitle(getCarContext().getString(labelResourcee)) - .setToggle( - new Toggle.Builder( - (value) -> { - writeSharedPref(prefKeyResource, value); - }) - .setChecked(readSharedPref(prefKeyResource, false)) - .build()) - .build(); - } - - private boolean readSharedPref(int keyResource, boolean defaultValue) { - return mSharedPref.getBoolean(getCarContext().getString(keyResource), defaultValue); - } - - private void writeSharedPref(int keyResource, boolean value) { - SharedPreferences.Editor editor = mSharedPref.edit(); - editor.putBoolean(getCarContext().getString(keyResource), value); - editor.commit(); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SurfaceRenderer.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SurfaceRenderer.java deleted file mode 100644 index 22cb497..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/car/SurfaceRenderer.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.car; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.Paint.Style; -import android.graphics.Rect; -import android.graphics.RectF; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.Log; -import android.view.Surface; - -import androidx.annotation.MainThread; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.AppManager; -import androidx.car.app.CarContext; -import androidx.car.app.SurfaceCallback; -import androidx.car.app.SurfaceContainer; -import androidx.car.app.sample.navigation.common.R; -import androidx.lifecycle.DefaultLifecycleObserver; -import androidx.lifecycle.Lifecycle; -import androidx.lifecycle.LifecycleOwner; - -/** A very simple implementation of a renderer for the app's background surface. */ -public final class SurfaceRenderer implements DefaultLifecycleObserver { - private static final String TAG = "SurfaceRenderer"; - - /** The maximum scale factor of the background map. */ - private static final float MAX_SCALE_FACTOR = 5f; - - /** The minimum scale factor of the background map. */ - private static final float MIN_SCALE_FACTOR = 0.5f; - - /** The scale factor to apply when initializing the background map. */ - private static final float MAP_ENLARGE_FACTOR = 5f; - - /** Looper msg to trigger a frame rendering */ - private static final int MSG_RENDER_FRAME = 1; - - @Nullable - Surface mSurface; - @Nullable - Rect mVisibleArea; - @Nullable - Rect mStableArea; - - private final CarContext mCarContext; - private final Paint mLeftInsetPaint = new Paint(); - private final Paint mRightInsetPaint = new Paint(); - private final Paint mCenterPaint = new Paint(); - private final Paint mMarkerPaint = new Paint(); - - private boolean mShowMarkers; - private int mNumMarkers; - private int mActiveMarker; - private String mLocationString = "unknown"; - - /** The bitmap that contains the background map image. */ - private final Bitmap mBackgroundMap; - - /** - * The transformation matrix for the background map image, to reflect the result of the user's - * pan and zoom actions. - */ - final Matrix mBackgroundMapMatrix = new Matrix(); - - /** The cumulative scale factor for the background map image. */ - float mCumulativeScaleFactor = 1f; - - /** - * The current horizontal center point of the background map, used to prevent the map from - * disappearing from pan actions. - */ - float mBackgroundMapCenterX = 0f; - - /** - * The current vertical center point of the background map, used to prevent the map from - * disappearing from pan actions. - */ - float mBackgroundMapCenterY = 0f; - - /** - * The original clip bounds of the background map, used to prevent the map from disappearing - * from pan actions. - */ - Rect mBackgroundMapClipBounds = new Rect(); - - public final SurfaceCallback mSurfaceCallback = - new SurfaceCallback() { - @Override - public void onSurfaceAvailable(@NonNull SurfaceContainer surfaceContainer) { - synchronized (SurfaceRenderer.this) { - Log.i(TAG, "Surface available " + surfaceContainer); - if (mSurface != null) { - mSurface.release(); - } - mSurface = surfaceContainer.getSurface(); - renderFrame(); - } - } - - @Override - public void onVisibleAreaChanged(@NonNull Rect visibleArea) { - synchronized (SurfaceRenderer.this) { - Log.i(TAG, "Visible area changed " + mSurface + ". stableArea: " - + mStableArea + " visibleArea:" + visibleArea); - mVisibleArea = visibleArea; - renderFrame(); - } - } - - @Override - public void onStableAreaChanged(@NonNull Rect stableArea) { - synchronized (SurfaceRenderer.this) { - Log.i(TAG, "Stable area changed " + mSurface + ". stableArea: " - + mStableArea + " visibleArea:" + mVisibleArea); - mStableArea = stableArea; - renderFrame(); - } - } - - @Override - public void onSurfaceDestroyed(@NonNull SurfaceContainer surfaceContainer) { - synchronized (SurfaceRenderer.this) { - Log.i(TAG, "Surface destroyed"); - if (mSurface != null) { - mSurface.release(); - mSurface = null; - } - } - } - - @Override - public void onScroll(float distanceX, float distanceY) { - synchronized (SurfaceRenderer.this) { - float newBackgroundCenterX = mBackgroundMapCenterX - distanceX; - float newBackgroundCenterY = mBackgroundMapCenterY - distanceY; - - // If the map stays within the clip bounds, pan the map. - if (mBackgroundMapClipBounds.contains((int) newBackgroundCenterX, - (int) newBackgroundCenterY)) { - mBackgroundMapCenterX = newBackgroundCenterX; - mBackgroundMapCenterY = newBackgroundCenterY; - mBackgroundMapMatrix.postTranslate(-distanceX, -distanceY); - renderFrame(); - } - } - } - - @Override - public void onScale(float focusX, float focusY, float scaleFactor) { - handleScale(focusX, focusY, scaleFactor); - } - }; - - private Handler mHandler = new Handler(Looper.getMainLooper()) { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case MSG_RENDER_FRAME: - doRenderFrame(); - } - } - }; - - public SurfaceRenderer(@NonNull CarContext carContext, @NonNull Lifecycle lifecycle) { - mCarContext = carContext; - - mLeftInsetPaint.setColor(Color.RED); - mLeftInsetPaint.setAntiAlias(true); - mLeftInsetPaint.setStyle(Style.STROKE); - - mRightInsetPaint.setColor(Color.RED); - mRightInsetPaint.setAntiAlias(true); - mRightInsetPaint.setStyle(Style.STROKE); - mRightInsetPaint.setTextAlign(Align.RIGHT); - - mCenterPaint.setColor(Color.BLUE); - mCenterPaint.setAntiAlias(true); - mCenterPaint.setStyle(Style.STROKE); - - mMarkerPaint.setColor(Color.GREEN); - mMarkerPaint.setAntiAlias(true); - mMarkerPaint.setStyle(Style.STROKE); - mMarkerPaint.setStrokeWidth(3); - - mBackgroundMap = BitmapFactory.decodeResource(carContext.getResources(), - R.drawable.map); - lifecycle.addObserver(this); - } - - @Override - public void onCreate(@NonNull LifecycleOwner owner) { - Log.i(TAG, "SurfaceRenderer created"); - mCarContext.getCarService(AppManager.class).setSurfaceCallback(mSurfaceCallback); - } - - /** Callback called when the car configuration changes. */ - public void onCarConfigurationChanged() { - renderFrame(); - } - - /** Handles the map zoom-in and zoom-out events. */ - public void handleScale(float focusX, float focusY, float scaleFactor) { - synchronized (this) { - float x = focusX; - float y = focusY; - - Rect visibleArea = mVisibleArea; - if (visibleArea != null) { - // If a focal point value is negative, use the center point of the visible area. - if (x < 0) { - x = visibleArea.centerX(); - } - if (y < 0) { - y = visibleArea.centerY(); - } - } - - // If the map stays between the maximum and minimum scale factors, scale the map. - float newCumulativeScaleFactor = mCumulativeScaleFactor * scaleFactor; - if (newCumulativeScaleFactor > MIN_SCALE_FACTOR - && newCumulativeScaleFactor < MAX_SCALE_FACTOR) { - mCumulativeScaleFactor = newCumulativeScaleFactor; - mBackgroundMapMatrix.postScale(scaleFactor, scaleFactor, x, y); - renderFrame(); - } - } - } - - /** Handles the map re-centering events. */ - public void handleRecenter() { - // Resetting the map matrix will trigger the initialization logic in renderFrame(). - mBackgroundMapMatrix.reset(); - renderFrame(); - } - - /** Updates the markers drawn on the surface. */ - public void updateMarkerVisibility(boolean showMarkers, int numMarkers, int activeMarker) { - mShowMarkers = showMarkers; - mNumMarkers = numMarkers; - mActiveMarker = activeMarker; - renderFrame(); - } - - /** Updates the location coordinate string drawn on the surface. */ - public void updateLocationString(@NonNull String locationString) { - mLocationString = locationString; - renderFrame(); - } - - void renderFrame() { - mHandler.sendEmptyMessage(MSG_RENDER_FRAME); - } - - @MainThread - void doRenderFrame() { - if (mSurface == null || !mSurface.isValid()) { - // Surface is not available, or has been destroyed, skip this frame. - return; - } - Canvas canvas = mSurface.lockCanvas(null); - - // Clear the background. - canvas.drawColor(mCarContext.isDarkMode() ? Color.DKGRAY : Color.LTGRAY); - - // Initialize the background map. - if (mBackgroundMapMatrix.isIdentity()) { - // Enlarge the original image. - RectF backgroundRect = new RectF(0, 0, mBackgroundMap.getWidth(), - mBackgroundMap.getHeight()); - RectF scaledBackgroundRect = new RectF(0, 0, - backgroundRect.width() * MAP_ENLARGE_FACTOR, - backgroundRect.height() * MAP_ENLARGE_FACTOR); - - // Initialize the cumulative scale factor and map center points. - mCumulativeScaleFactor = 1f; - mBackgroundMapCenterX = scaledBackgroundRect.centerX(); - mBackgroundMapCenterY = scaledBackgroundRect.centerY(); - - // Move to the center of the enlarged map. - mBackgroundMapMatrix.setRectToRect(backgroundRect, scaledBackgroundRect, - Matrix.ScaleToFit.FILL); - mBackgroundMapMatrix.postTranslate( - -mBackgroundMapCenterX + canvas.getClipBounds().centerX(), - -mBackgroundMapCenterY + canvas.getClipBounds().centerY()); - scaledBackgroundRect.round(mBackgroundMapClipBounds); - } - canvas.drawBitmap(mBackgroundMap, mBackgroundMapMatrix, null); - - - final int horizontalTextMargin = 10; - final int verticalTextMarginFromTop = 20; - final int verticalTextMarginFromBottom = 10; - - // Draw a rectangle showing the inset. - Rect visibleArea = mVisibleArea; - if (visibleArea != null) { - if (visibleArea.isEmpty()) { - // No inset set. The entire area is considered safe to draw. - visibleArea.set(0, 0, canvas.getWidth() - 1, canvas.getHeight() - 1); - } - - canvas.drawRect(visibleArea, mLeftInsetPaint); - canvas.drawLine( - visibleArea.left, - visibleArea.top, - visibleArea.right, - visibleArea.bottom, - mLeftInsetPaint); - canvas.drawLine( - visibleArea.right, - visibleArea.top, - visibleArea.left, - visibleArea.bottom, - mLeftInsetPaint); - canvas.drawText( - "(" + visibleArea.left + " , " + visibleArea.top + ")", - visibleArea.left + horizontalTextMargin, - visibleArea.top + verticalTextMarginFromTop, - mLeftInsetPaint); - canvas.drawText( - "(" + visibleArea.right + " , " + visibleArea.bottom + ")", - visibleArea.right - horizontalTextMargin, - visibleArea.bottom - verticalTextMarginFromBottom, - mRightInsetPaint); - - // Draw location on the top right corner of the screen. - canvas.drawText( - "(" + mLocationString + ")", - visibleArea.right - horizontalTextMargin, - visibleArea.top + verticalTextMarginFromTop, - mRightInsetPaint); - } else { - Log.d(TAG, "Visible area not available."); - } - - if (mStableArea != null) { - // Draw a cross-hairs at the stable center. - final int lengthPx = 15; - int centerX = mStableArea.centerX(); - int centerY = mStableArea.centerY(); - canvas.drawLine(centerX - lengthPx, centerY, centerX + lengthPx, centerY, mCenterPaint); - canvas.drawLine(centerX, centerY - lengthPx, centerX, centerY + lengthPx, mCenterPaint); - canvas.drawText( - "(" + centerX + ", " + centerY + ")", - centerX + horizontalTextMargin, - centerY, - mCenterPaint); - } else { - Log.d(TAG, "Stable area not available."); - } - - if (mShowMarkers) { - // Show a set number of markers centered around the midpoint of the stable area. If no - // stable area, then use visible area or canvas dimensions. If an active marker is set - // draw - // a line from the center to that marker. - Rect markerArea = - mStableArea != null - ? mStableArea - : (mVisibleArea != null - ? mVisibleArea - : new Rect(0, 0, canvas.getWidth() - 1, canvas.getHeight())); - int centerX = markerArea.centerX(); - int centerY = markerArea.centerY(); - double radius = Math.min(centerX / 2, centerY / 2); - - double circleAngle = 2.0d * Math.PI; - double markerpiece = circleAngle / mNumMarkers; - for (int i = 0; i < mNumMarkers; i++) { - int markerX = centerX + (int) (radius * Math.cos(markerpiece * i)); - int markerY = centerY + (int) (radius * Math.sin(markerpiece * i)); - canvas.drawCircle(markerX, markerY, 5, mMarkerPaint); - if (i == mActiveMarker) { - canvas.drawLine(centerX, centerY, markerX, markerY, mMarkerPaint); - } - } - } - - mSurface.unlockCanvasAndPost(canvas); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/DemoScripts.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/DemoScripts.java deleted file mode 100644 index 3bf0aa8..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/DemoScripts.java +++ /dev/null @@ -1,578 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.model; - -import static androidx.car.app.navigation.model.LaneDirection.SHAPE_NORMAL_RIGHT; -import static androidx.car.app.navigation.model.LaneDirection.SHAPE_STRAIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_DEPART; -import static androidx.car.app.navigation.model.Maneuver.TYPE_DESTINATION; -import static androidx.car.app.navigation.model.Maneuver.TYPE_DESTINATION_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_DESTINATION_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_DESTINATION_STRAIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_FERRY_BOAT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_FERRY_TRAIN; -import static androidx.car.app.navigation.model.Maneuver.TYPE_FORK_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_FORK_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_KEEP_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_KEEP_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_MERGE_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_MERGE_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_MERGE_SIDE_UNSPECIFIED; -import static androidx.car.app.navigation.model.Maneuver.TYPE_NAME_CHANGE; -import static androidx.car.app.navigation.model.Maneuver.TYPE_OFF_RAMP_NORMAL_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_OFF_RAMP_NORMAL_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_OFF_RAMP_SLIGHT_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_OFF_RAMP_SLIGHT_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_NORMAL_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_NORMAL_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_SHARP_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_SHARP_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_SLIGHT_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_SLIGHT_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_U_TURN_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ON_RAMP_U_TURN_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW_WITH_ANGLE; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_CCW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_ENTER_CW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_EXIT_CCW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_ROUNDABOUT_EXIT_CW; -import static androidx.car.app.navigation.model.Maneuver.TYPE_STRAIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_NORMAL_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_NORMAL_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_SHARP_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_SHARP_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_SLIGHT_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_TURN_SLIGHT_RIGHT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_UNKNOWN; -import static androidx.car.app.navigation.model.Maneuver.TYPE_U_TURN_LEFT; -import static androidx.car.app.navigation.model.Maneuver.TYPE_U_TURN_RIGHT; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.CarContext; -import androidx.car.app.model.CarColor; -import androidx.car.app.model.CarIcon; -import androidx.car.app.model.DateTimeWithZone; -import androidx.car.app.model.Distance; -import androidx.car.app.navigation.model.Destination; -import androidx.car.app.navigation.model.Lane; -import androidx.car.app.navigation.model.LaneDirection; -import androidx.car.app.navigation.model.Maneuver; -import androidx.car.app.navigation.model.Step; -import androidx.car.app.navigation.model.TravelEstimate; -import androidx.car.app.sample.navigation.common.R; -import androidx.core.graphics.drawable.IconCompat; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - -/** - * Example scripts to "control" navigation within the app. - * - *

The script takes the form of a list of instructions which can be passed to different parts of - * the app. This is the central location where scripts are stored. - * - *

The scripts start with a setup phase where all destinations and steps are added to the - * instruction list. Then navigation updates are added for each step to simulate driving. - * - *

>The setup phases consists of: - * - *

    - *
  • Start Navigation - *
  • Add the destination information. - *
  • Add 4 intermediate steps to the destination. - *
- * - *

The navigation phase consists of - * - *

    - *
  • Add positions along the route getting closer to the step. - *
  • Once the step is reached, pop the step. If more steps remain go back to adding more - * positions. - *
  • When no more steps remain set the arrived state. - *
  • End Navigation - *
- * - *

There are several helper functions including {@link #generateTripUpdateSequence} which - * interpolates a straight path and generates all the updates for a step. - */ -public class DemoScripts { - - private static final long INSTRUCTION_NO_ELAPSED_TIME = 0; - private static final int SPEED_METERS_PER_SEC = 5; - private static final int DISTANCE_METERS = 450; - - /** Create instructions for home. */ - @NonNull - public static List getNavigateHome(@NonNull CarContext carContext) { - ArrayList instructions = new ArrayList<>(); - - DateTimeWithZone arrivalTimeAtDestination = getCurrentDateTimeZoneWithOffset(30); - - CarIcon lanesImage = - new CarIcon.Builder(IconCompat.createWithResource(carContext, R.drawable.lanes)) - .build(); - CarIcon junctionImage = - new CarIcon.Builder( - IconCompat.createWithResource( - carContext, - R.drawable.junction_image)) - .build(); - - Lane straightNormal = - new Lane.Builder() - .addDirection(LaneDirection.create(SHAPE_STRAIGHT, false)) - .build(); - Lane rightHighlighted = - new Lane.Builder() - .addDirection(LaneDirection.create(SHAPE_NORMAL_RIGHT, true)) - .build(); - - int step1IconResourceId = - getTurnIconResourceId(Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE); - Step step1 = - new Step.Builder("State Street") - .setManeuver( - getManeuverWithExitNumberAndAngle( - carContext, - Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE, - step1IconResourceId, - 2, - 270)) - .setRoad("State Street") - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(rightHighlighted) - .setLanesImage(lanesImage) - .build(); - int step2IconResourceId = getTurnIconResourceId(Maneuver.TYPE_TURN_NORMAL_LEFT); - Step step2 = - new Step.Builder("Kirkland Way") - .setManeuver( - getManeuver( - carContext, - Maneuver.TYPE_TURN_NORMAL_LEFT, - step2IconResourceId)) - .setRoad("Kirkland Way") - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(rightHighlighted) - .setLanesImage(lanesImage) - .build(); - int step3IconResourceId = getTurnIconResourceId(Maneuver.TYPE_TURN_NORMAL_RIGHT); - Step step3 = - new Step.Builder("6th Street.") - .setManeuver( - getManeuver( - carContext, - Maneuver.TYPE_TURN_NORMAL_RIGHT, - step3IconResourceId)) - .setRoad("6th Street.") - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(straightNormal) - .addLane(rightHighlighted) - .setLanesImage(lanesImage) - .build(); - int step4IconResourceId = getTurnIconResourceId(Maneuver.TYPE_DESTINATION_RIGHT); - Step step4 = - new Step.Builder("Google Kirkland.") - .setManeuver( - getManeuver( - carContext, TYPE_DESTINATION_RIGHT, step4IconResourceId)) - .setRoad("Google Kirkland.") - .build(); - - // Start the navigation and add destination and steps. - instructions.add( - Instruction.builder(Instruction.Type.START_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .build()); - - Destination destination = - new Destination.Builder().setName("Work").setAddress("747 6th St.").build(); - instructions.add( - Instruction.builder( - Instruction.Type.ADD_DESTINATION_NAVIGATION, - INSTRUCTION_NO_ELAPSED_TIME) - .setDestination(destination) - .build()); - - instructions.add( - Instruction.builder(Instruction.Type.SET_REROUTING, TimeUnit.SECONDS.toMillis(5)) - .setDestinationTravelEstimate( - new TravelEstimate.Builder( - Distance.create(350, Distance.UNIT_METERS), - arrivalTimeAtDestination) - .setRemainingTimeSeconds( - /* remainingTimeSeconds= */ DISTANCE_METERS - / SPEED_METERS_PER_SEC) - .build()) - .setNotification( - true, - carContext.getString(R.string.navigation_rerouting), - null, - R.drawable.ic_launcher) - .build()); - - instructions.add( - Instruction.builder( - Instruction.Type.ADD_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .setStep(step1) - .build()); - instructions.add( - Instruction.builder( - Instruction.Type.ADD_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .setStep(step2) - .build()); - instructions.add( - Instruction.builder( - Instruction.Type.ADD_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .setStep(step3) - .build()); - instructions.add( - Instruction.builder( - Instruction.Type.ADD_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .setStep(step4) - .build()); - - // Add trip positions for each step. - int updateDistanceRemaining = DISTANCE_METERS; - instructions.addAll( - generateTripUpdateSequence( - /* count= */ 4, - /* startDestinationDistanceRemaining= */ updateDistanceRemaining, - /* startStepDistanceRemaining= */ 100, - arrivalTimeAtDestination, - "3rd Street", - junctionImage, - /* showLanes= */ true, - "onto State Street", - SPEED_METERS_PER_SEC, - step1IconResourceId)); - instructions.add( - Instruction.builder( - Instruction.Type.POP_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .build()); - updateDistanceRemaining -= 100; - - instructions.addAll( - generateTripUpdateSequence( - /* count= */ 6, - /* startDestinationDistanceRemaining= */ updateDistanceRemaining, - /* startStepDistanceRemaining= */ 150, - arrivalTimeAtDestination, - "State Street", - junctionImage, - /* showLanes= */ true, - "onto Kirkland Way", - SPEED_METERS_PER_SEC, - step2IconResourceId)); - instructions.add( - Instruction.builder( - Instruction.Type.POP_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .build()); - updateDistanceRemaining -= 150; - - instructions.addAll( - generateTripUpdateSequence( - /* count= */ 4, - /* startDestinationDistanceRemaining= */ updateDistanceRemaining, - /* startStepDistanceRemaining= */ 100, - arrivalTimeAtDestination, - "Kirkland Way", - junctionImage, - /* showLanes= */ true, - "onto 6th Street", - SPEED_METERS_PER_SEC, - step3IconResourceId)); - instructions.add( - Instruction.builder( - Instruction.Type.POP_STEP_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .build()); - updateDistanceRemaining -= 100; - - instructions.addAll( - generateTripUpdateSequence( - /* count= */ 4, - /* startDestinationDistanceRemaining= */ updateDistanceRemaining, - /* startStepDistanceRemaining= */ 100, - arrivalTimeAtDestination, - "6th Street", - /* junctionImage= */ null, - /* showLanes= */ false, - "to Google Kirkland on right", - SPEED_METERS_PER_SEC, - step4IconResourceId)); - - // Set arrived state and then stop navigation. - instructions.add( - Instruction.builder(Instruction.Type.SET_ARRIVED, TimeUnit.SECONDS.toMillis(5)) - .build()); - - instructions.add( - Instruction.builder(Instruction.Type.POP_DESTINATION_NAVIGATION, - INSTRUCTION_NO_ELAPSED_TIME) - .build()); - instructions.add( - Instruction.builder(Instruction.Type.END_NAVIGATION, INSTRUCTION_NO_ELAPSED_TIME) - .build()); - return instructions; - } - - private static DateTimeWithZone getCurrentDateTimeZoneWithOffset(int offsetSeconds) { - GregorianCalendar startTime = new GregorianCalendar(); - GregorianCalendar destinationETA = (GregorianCalendar) startTime.clone(); - destinationETA.add(Calendar.SECOND, offsetSeconds); - return getDateTimeZone(destinationETA); - } - - /** Convenience function to create the date formmat. */ - private static DateTimeWithZone getDateTimeZone(GregorianCalendar calendar) { - Date date = calendar.getTime(); - TimeZone timeZone = calendar.getTimeZone(); - - long timeSinceEpochMillis = date.getTime(); - long timeZoneOffsetSeconds = - MILLISECONDS.toSeconds(timeZone.getOffset(timeSinceEpochMillis)); - String zoneShortName = "PST"; - - return DateTimeWithZone.create( - timeSinceEpochMillis, (int) timeZoneOffsetSeconds, zoneShortName); - } - - /** - * Generates all the updates for a particular step interpolating along a straight line. - * - * @param count number of instructions to generate until the next - * step - * @param startDestinationDistanceRemaining the distance until the final destination at the - * start of the sequence - * @param startStepDistanceRemaining the distance until the next step at the start of the - * sequence - * @param arrivalTimeAtDestination the arrival time at the destination - * @param currentRoad the name of the road currently being travelled - * @param junctionImage photo realistic image of upcoming turn - * @param showLanes indicates if the lane info should be shown for - * this maneuver - * @param speed meters/second being traveled - * @return sequence of instructions until the next step - */ - private static List generateTripUpdateSequence( - int count, - int startDestinationDistanceRemaining, - int startStepDistanceRemaining, - DateTimeWithZone arrivalTimeAtDestination, - String currentRoad, - @Nullable CarIcon junctionImage, - boolean showLanes, - String nextInstruction, - int speed, - int notificationIcon) { - List sequence = new ArrayList<>(count); - int destinationDistanceRemaining = startDestinationDistanceRemaining; - int stepDistanceRemaining = startStepDistanceRemaining; - int distanceIncrement = startStepDistanceRemaining / count; - boolean notify = true; - - for (int i = 0; i < count; i++) { - Distance remainingDistance = - Distance.create(stepDistanceRemaining, Distance.UNIT_METERS); - TravelEstimate destinationTravelEstimate = - new TravelEstimate.Builder( - Distance.create( - destinationDistanceRemaining, Distance.UNIT_METERS), - arrivalTimeAtDestination) - .setRemainingTimeSeconds(destinationDistanceRemaining / speed) - .setRemainingTimeColor(CarColor.YELLOW) - .setRemainingDistanceColor(CarColor.GREEN) - .build(); - TravelEstimate stepTravelEstimate = - new TravelEstimate.Builder( - remainingDistance, - getCurrentDateTimeZoneWithOffset(distanceIncrement)) - .setRemainingTimeSeconds(/* remainingTimeSeconds= */ distanceIncrement) - .build(); - String notificationTitle = String.format("%dm", stepDistanceRemaining); - Instruction.Builder instruction = - Instruction.builder( - Instruction.Type.SET_TRIP_POSITION_NAVIGATION, - TimeUnit.SECONDS.toMillis(distanceIncrement / speed)) - .setStepRemainingDistance(remainingDistance) - .setStepTravelEstimate(stepTravelEstimate) - .setDestinationTravelEstimate(destinationTravelEstimate) - .setRoad(currentRoad) - .setNotification( - notify, notificationTitle, nextInstruction, notificationIcon); - // Don't show lanes in the first and last part of the maneuver. In the middle part of - // the - // maneuver use the passed parameter to determine if lanes should be shown. - if (i == 0) { - instruction.setShouldShowLanes(false).setShouldShowNextStep(true); - } else if (i == 1) { - instruction.setShouldShowLanes(showLanes).setShouldShowNextStep(true); - } else if (i == 2) { - instruction.setShouldShowLanes(showLanes).setShouldShowNextStep(false); - } else { - instruction - .setShouldShowLanes(false) - .setShouldShowNextStep(false) - .setJunctionImage(junctionImage); - } - sequence.add(instruction.build()); - - destinationDistanceRemaining -= distanceIncrement; - stepDistanceRemaining -= distanceIncrement; - notify = false; - } - return sequence; - } - - /** Returns a maneuver with image selected from resources. */ - private static Maneuver getManeuver( - @NonNull CarContext carContext, int type, int iconResourceId) { - return new Maneuver.Builder(type).setIcon(getCarIcon(carContext, iconResourceId)).build(); - } - - /** - * Returns a maneuver that includes an exit number and angle with image selected from resources. - */ - private static Maneuver getManeuverWithExitNumberAndAngle( - @NonNull CarContext carContext, - int type, - int iconResourceId, - int exitNumber, - int exitAngle) { - return new Maneuver.Builder(type) - .setIcon(getCarIcon(carContext, iconResourceId)) - .setRoundaboutExitNumber(exitNumber) - .setRoundaboutExitAngle(exitAngle) - .build(); - } - - /** Generates a {@link CarIcon} representing the turn. */ - private static CarIcon getCarIcon(@NonNull CarContext carContext, int resourceId) { - return new CarIcon.Builder(IconCompat.createWithResource(carContext, resourceId)).build(); - } - - private static int getTurnIconResourceId(int type) { - int resourceId = R.drawable.ic_launcher; - switch (type) { - case TYPE_TURN_NORMAL_LEFT: - resourceId = R.drawable.ic_turn_normal_left; - break; - case TYPE_TURN_NORMAL_RIGHT: - resourceId = R.drawable.ic_turn_normal_right; - break; - case TYPE_UNKNOWN: - case TYPE_DEPART: - case TYPE_STRAIGHT: - resourceId = R.drawable.ic_turn_name_change; - break; - case TYPE_DESTINATION: - case TYPE_DESTINATION_STRAIGHT: - case TYPE_DESTINATION_RIGHT: - case TYPE_DESTINATION_LEFT: - resourceId = R.drawable.ic_turn_destination; - break; - case TYPE_NAME_CHANGE: - resourceId = R.drawable.ic_turn_name_change; - break; - case TYPE_KEEP_LEFT: - case TYPE_TURN_SLIGHT_LEFT: - resourceId = R.drawable.ic_turn_slight_left; - break; - case TYPE_KEEP_RIGHT: - case TYPE_TURN_SLIGHT_RIGHT: - resourceId = R.drawable.ic_turn_slight_right; - break; - case TYPE_TURN_SHARP_LEFT: - resourceId = R.drawable.ic_turn_sharp_left; - break; - case TYPE_TURN_SHARP_RIGHT: - resourceId = R.drawable.ic_turn_sharp_right; - break; - case TYPE_U_TURN_LEFT: - resourceId = R.drawable.ic_turn_u_turn_left; - break; - case TYPE_U_TURN_RIGHT: - resourceId = R.drawable.ic_turn_u_turn_right; - break; - case TYPE_ON_RAMP_SLIGHT_LEFT: - case TYPE_ON_RAMP_NORMAL_LEFT: - case TYPE_ON_RAMP_SHARP_LEFT: - case TYPE_ON_RAMP_U_TURN_LEFT: - case TYPE_OFF_RAMP_SLIGHT_LEFT: - case TYPE_OFF_RAMP_NORMAL_LEFT: - case TYPE_FORK_LEFT: - resourceId = R.drawable.ic_turn_fork_left; - break; - case TYPE_ON_RAMP_SLIGHT_RIGHT: - case TYPE_ON_RAMP_NORMAL_RIGHT: - case TYPE_ON_RAMP_SHARP_RIGHT: - case TYPE_ON_RAMP_U_TURN_RIGHT: - case TYPE_OFF_RAMP_SLIGHT_RIGHT: - case TYPE_OFF_RAMP_NORMAL_RIGHT: - case TYPE_FORK_RIGHT: - resourceId = R.drawable.ic_turn_fork_right; - break; - case TYPE_MERGE_LEFT: - case TYPE_MERGE_RIGHT: - case TYPE_MERGE_SIDE_UNSPECIFIED: - resourceId = R.drawable.ic_turn_merge_symmetrical; - break; - case TYPE_ROUNDABOUT_ENTER_CW: - case TYPE_ROUNDABOUT_ENTER_CCW: - case TYPE_ROUNDABOUT_EXIT_CW: - case TYPE_ROUNDABOUT_EXIT_CCW: - resourceId = R.drawable.ic_turn_name_change; - break; - case TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW: - case TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW_WITH_ANGLE: - resourceId = R.drawable.ic_roundabout_cw; - break; - case TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW: - case TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE: - resourceId = R.drawable.ic_roundabout_ccw; - break; - case TYPE_FERRY_BOAT: - case TYPE_FERRY_TRAIN: - resourceId = R.drawable.ic_turn_name_change; - break; - default: - throw new IllegalStateException("Unexpected maneuver type: " + type); - } - return resourceId; - } - - private DemoScripts() { - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Instruction.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Instruction.java deleted file mode 100644 index ebcdc26..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Instruction.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.model; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.car.app.model.CarIcon; -import androidx.car.app.model.Distance; -import androidx.car.app.navigation.model.Destination; -import androidx.car.app.navigation.model.Step; -import androidx.car.app.navigation.model.TravelEstimate; - -/** - * Container for scripting navigation instructions. - * - *

Each {@link Instruction} represents a change (delta) in the state of navigation corresponding - * to a change in state that could occur during a real navigation session. In general a script - * follows the following rough outline similar to a driving sessions: - * - *

    - *
  • Start Navigation - *
  • Add one or more destinations (as would be selected by a driver) - *
  • Add one or more steps (as would be provided by a routing algorithm) - *
  • Add updated positions until the next step is reached. - *
  • pop a step and send positions until the next step is reached. - *
  • Repeat until all steps are popped. - *
  • End Navigation. - *
- * - *

In addition to a {@link Type}, each instruction specifies the duration until the next - * instruction should be executed. A duration of zero allows multiple instructions to be stacked up - * as if they were a single instruction. All other parameters are optional and related directly to - * which instruction is specified. - */ -public class Instruction { - - public enum Type { - START_NAVIGATION, - END_NAVIGATION, - ADD_DESTINATION_NAVIGATION, - POP_DESTINATION_NAVIGATION, - ADD_STEP_NAVIGATION, - POP_STEP_NAVIGATION, - SET_REROUTING, - SET_ARRIVED, - SET_TRIP_POSITION_NAVIGATION, - } - - ; - - private final Type mType; - private final long mDurationMillis; - - // Only support a single destination at the moment. - @Nullable - private final Destination mDestination; - - // Only support setting a single step. - @Nullable - private final Step mStep; - @Nullable - private final Distance mStepRemainingDistance; - @Nullable - private final TravelEstimate mStepTravelEstimate; - @Nullable - private final TravelEstimate mDestinationTravelEstimate; - @Nullable - private final String mRoad; - private final boolean mShouldShowNextStep; - private final boolean mShouldShowLanes; - @Nullable - private final CarIcon mJunctionImage; - - @Nullable - private final String mNotificationTitle; - @Nullable - private final String mNotificationContent; - private final int mNotificationIcon; - private final boolean mShouldNotify; - - /** Constructs a new builder of {@link Instruction}. */ - @NonNull - public static Builder builder(@NonNull Type type, long lengthMs) { - return new Builder(type, lengthMs); - } - - public long getDurationMillis() { - return mDurationMillis; - } - - @NonNull - public Type getType() { - return mType; - } - - @Nullable - public Destination getDestination() { - return mDestination; - } - - @Nullable - public Step getStep() { - return mStep; - } - - @Nullable - public Distance getStepRemainingDistance() { - return mStepRemainingDistance; - } - - @Nullable - public TravelEstimate getStepTravelEstimate() { - return mStepTravelEstimate; - } - - @Nullable - public TravelEstimate getDestinationTravelEstimate() { - return mDestinationTravelEstimate; - } - - @Nullable - public String getRoad() { - return mRoad; - } - - public boolean getShouldShowNextStep() { - return mShouldShowNextStep; - } - - public boolean getShouldShowLanes() { - return mShouldShowLanes; - } - - @Nullable - public CarIcon getJunctionImage() { - return mJunctionImage; - } - - @Nullable - public String getNotificationTitle() { - return mNotificationTitle; - } - - @Nullable - public String getNotificationContent() { - return mNotificationContent; - } - - public int getNotificationIcon() { - return mNotificationIcon; - } - - public boolean getShouldNotify() { - return mShouldNotify; - } - - Instruction(Builder builder) { - mType = builder.mType; - mDurationMillis = builder.mDurationMillis; - mDestination = builder.mDestination; - mStep = builder.mStep; - mStepRemainingDistance = builder.mStepRemainingDistance; - mStepTravelEstimate = builder.mStepTravelEstimate; - mDestinationTravelEstimate = builder.mDestinationTravelEstimate; - mRoad = builder.mRoad; - mShouldShowNextStep = builder.mShouldShowNextStep; - mShouldShowLanes = builder.mShouldShowLanes; - mJunctionImage = builder.mJunctionImage; - mNotificationTitle = builder.mNotificationTitle; - mNotificationContent = builder.mNotificationContent; - mNotificationIcon = builder.mNotificationIcon; - mShouldNotify = builder.mShouldNotify; - } - - /** Builder for creating an {@link Instruction}. */ - public static final class Builder { - Type mType; - long mDurationMillis; - @Nullable - Destination mDestination; - @Nullable - Step mStep; - @Nullable - Distance mStepRemainingDistance; - @Nullable - TravelEstimate mStepTravelEstimate; - @Nullable - TravelEstimate mDestinationTravelEstimate; - @Nullable - String mRoad; - boolean mShouldShowNextStep; - boolean mShouldShowLanes; - @Nullable - CarIcon mJunctionImage; - - @Nullable - String mNotificationTitle; - @Nullable - String mNotificationContent; - int mNotificationIcon; - boolean mShouldNotify; - - public Builder(@NonNull Type type, long durationMillis) { - mType = type; - mDurationMillis = durationMillis; - } - - Builder setDestination(@Nullable Destination destination) { - mDestination = destination; - return this; - } - - Builder setStep(@Nullable Step step) { - mStep = step; - return this; - } - - Builder setStepRemainingDistance(@Nullable Distance stepRemainingDistance) { - mStepRemainingDistance = stepRemainingDistance; - return this; - } - - Builder setStepTravelEstimate(@Nullable TravelEstimate stepTravelEstimate) { - mStepTravelEstimate = stepTravelEstimate; - return this; - } - - Builder setDestinationTravelEstimate(@Nullable TravelEstimate destinationTravelEstimate) { - mDestinationTravelEstimate = destinationTravelEstimate; - return this; - } - - Builder setRoad(@Nullable String road) { - mRoad = road; - return this; - } - - Builder setShouldShowNextStep(boolean shouldShowNextStep) { - mShouldShowNextStep = shouldShowNextStep; - return this; - } - - Builder setShouldShowLanes(boolean shouldShowLanes) { - mShouldShowLanes = shouldShowLanes; - return this; - } - - Builder setJunctionImage(@Nullable CarIcon junctionImage) { - mJunctionImage = junctionImage; - return this; - } - - Builder setNotification( - boolean shouldNotify, - @Nullable String notificationTitle, - @Nullable String notificationContent, - int notificationIcon) { - mNotificationTitle = notificationTitle; - mNotificationContent = notificationContent; - mShouldNotify = shouldNotify; - mNotificationIcon = notificationIcon; - return this; - } - - /** Constructs the {@link Instruction} defined by this builder. */ - @NonNull - public Instruction build() { - return new Instruction(this); - } - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Script.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Script.java deleted file mode 100644 index d7f8650..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/model/Script.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.model; - -import android.os.Handler; -import android.os.Looper; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.List; - -/** Represents an instruction sequence and parameters for a executing a script. */ -public class Script { - - private final Handler mHandler = new Handler(Looper.getMainLooper()); - private final List mInstructions; - private final Processor mProcessor; - private int mCurrentInstruction; - - /** An interface for a block of code that processes an instruction. */ - public interface Processor { - /** A block of code that processes an instruction. */ - void process(@NonNull Instruction instruction, @Nullable Instruction nextInstruction); - } - - /** Executes the given list of instructions. */ - @NonNull - public static Script execute(@NonNull List instructions, - @NonNull Processor processor) { - return new Script(instructions, processor); - } - - /** Stops executing the instructions. */ - public void stop() { - mHandler.removeCallbacksAndMessages(null); - mCurrentInstruction = mInstructions.size(); - } - - private Script(@NonNull List instructions, @NonNull Processor processor) { - mInstructions = instructions; - mProcessor = processor; - mCurrentInstruction = 0; - // Execute the first instruction right away to start navigation and avoid flicker. - nextInstruction(); - } - - private void nextInstruction() { - if (mCurrentInstruction >= mInstructions.size()) { - // Script is finished. - return; - } - Instruction instruction = mInstructions.get(mCurrentInstruction); - Instruction nextInstruction = null; - int nextPosition = mCurrentInstruction + 1; - if (nextPosition < mInstructions.size()) { - nextInstruction = mInstructions.get(nextPosition); - } - mProcessor.process(instruction, nextInstruction); - mCurrentInstruction++; - mHandler.postDelayed(this::nextInstruction, instruction.getDurationMillis()); - } -} diff --git a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/nav/NavigationService.java b/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/nav/NavigationService.java deleted file mode 100644 index 209122c..0000000 --- a/car_app_library/navigation/common/src/main/java/androidx/car/app/sample/navigation/common/nav/NavigationService.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * http://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 androidx.car.app.sample.navigation.common.nav; - -import static android.media.AudioManager.AUDIOFOCUS_REQUEST_GRANTED; - -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.ComponentName; -import android.content.Intent; -import android.content.res.AssetFileDescriptor; -import android.graphics.BitmapFactory; -import android.media.AudioAttributes; -import android.media.AudioFocusRequest; -import android.media.AudioManager; -import android.media.MediaPlayer; -import android.os.Binder; -import android.os.Build; -import android.os.IBinder; -import android.text.TextUtils; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.RawRes; -import androidx.car.app.CarContext; -import androidx.car.app.CarToast; -import androidx.car.app.model.CarIcon; -import androidx.car.app.model.Distance; -import androidx.car.app.navigation.NavigationManager; -import androidx.car.app.navigation.NavigationManagerCallback; -import androidx.car.app.navigation.model.Destination; -import androidx.car.app.navigation.model.Step; -import androidx.car.app.navigation.model.TravelEstimate; -import androidx.car.app.navigation.model.Trip; -import androidx.car.app.notification.CarAppExtender; -import androidx.car.app.notification.CarPendingIntent; -import androidx.car.app.sample.navigation.common.R; -import androidx.car.app.sample.navigation.common.app.MainActivity; -import androidx.car.app.sample.navigation.common.car.NavigationCarAppService; -import androidx.car.app.sample.navigation.common.model.Instruction; -import androidx.car.app.sample.navigation.common.model.Script; -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationManagerCompat; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** Foreground service to provide navigation directions. */ -public class NavigationService extends Service { - private static final String TAG = "NavigationService"; - - public static final String DEEP_LINK_ACTION = "androidx.car.app.samples.navigation.car" - + ".NavigationDeepLinkAction"; - public static final String CHANNEL_ID = "NavigationServiceChannel"; - - /** The identifier for the navigation notification displayed for the foreground service. */ - private static final int NAV_NOTIFICATION_ID = 87654321; - - /** The identifier for the non-navigation notifications, such as a traffic accident warning. */ - private static final int NOTIFICATION_ID = 77654321; - - // Constants for location broadcast - private static final String PACKAGE_NAME = - "androidx.car.app.sample.navigation.common.nav.navigationservice"; - - private static final String EXTRA_STARTED_FROM_NOTIFICATION = - PACKAGE_NAME + ".started_from_notification"; - public static final String CANCEL_ACTION = "CANCEL"; - - private NotificationManager mNotificationManager; - private final IBinder mBinder = new LocalBinder(); - - @Nullable - private CarContext mCarContext; - - @Nullable - private Listener mListener; - - @Nullable - private NavigationManager mNavigationManager; - private boolean mIsNavigating; - private int mStepsSent; - - private List mDestinations = new ArrayList<>(); - private List mSteps = new ArrayList<>(); - - @Nullable - private Script mScript; - - /** A listener for the navigation state changes. */ - public interface Listener { - /** Callback called when the navigation state changes. */ - void navigationStateChanged( - boolean isNavigating, - boolean isRerouting, - boolean hasArrived, - @Nullable List destinations, - @Nullable List steps, - @Nullable TravelEstimate nextDestinationTravelEstimate, - @Nullable Distance nextStepRemainingDistance, - boolean shouldShowNextStep, - boolean shouldShowLanes, - @Nullable CarIcon junctionImage); - } - - /** - * Class used for the client Binder. Since this service runs in the same process as its clients, - * we don't need to deal with IPC. - */ - public class LocalBinder extends Binder { - @NonNull - public NavigationService getService() { - return NavigationService.this; - } - } - - @Override - public void onCreate() { - Log.i(TAG, "In onCreate()"); - createNotificationChannel(); - } - - @Override - public int onStartCommand(@NonNull Intent intent, int flags, int startId) { - Log.i(TAG, "In onStartCommand()"); - if (CANCEL_ACTION.equals(intent.getAction())) { - stopNavigation(); - } - return START_NOT_STICKY; - } - - @Nullable - @Override - public IBinder onBind(@NonNull Intent intent) { - return mBinder; - } - - @Override - public boolean onUnbind(@NonNull Intent intent) { - return true; // Ensures onRebind() is called when a client re-binds. - } - - /** Sets the {@link CarContext} to use while the service is connected. */ - public void setCarContext(@NonNull CarContext carContext, @NonNull Listener listener) { - mCarContext = carContext; - mNavigationManager = mCarContext.getCarService(NavigationManager.class); - mNavigationManager.setNavigationManagerCallback( - new NavigationManagerCallback() { - @Override - public void onStopNavigation() { - NavigationService.this.stopNavigation(); - } - - @Override - public void onAutoDriveEnabled() { - Log.d(TAG, "onAutoDriveEnabled called"); - CarToast.makeText(carContext, "Auto drive enabled", CarToast.LENGTH_LONG) - .show(); - } - }); - mListener = listener; - - // Uncomment if navigating - // mNavigationManager.navigationStarted(); - } - - /** Clears the currently used {@link CarContext}. */ - public void clearCarContext() { - mCarContext = null; - mNavigationManager = null; - } - - /** Executes the given list of navigation instructions. */ - public void executeInstructions(@NonNull List instructions) { - mScript = - Script.execute( - instructions, - (instruction, nextInstruction) -> { - switch (instruction.getType()) { - case START_NAVIGATION: - startNavigation(); - break; - case END_NAVIGATION: - endNavigationFromScript(); - break; - case ADD_DESTINATION_NAVIGATION: - Destination destination = instruction.getDestination(); - mDestinations.add(destination); - break; - case POP_DESTINATION_NAVIGATION: - mDestinations.remove(0); - break; - case ADD_STEP_NAVIGATION: - Step step = instruction.getStep(); - mSteps.add(step); - break; - case POP_STEP_NAVIGATION: - mSteps.remove(0); - break; - case SET_TRIP_POSITION_NAVIGATION: - if (mIsNavigating) { - TravelEstimate destinationTravelEstimate = - instruction.getDestinationTravelEstimate(); - TravelEstimate stepTravelEstimate = - instruction.getStepTravelEstimate(); - Trip.Builder tripBuilder = new Trip.Builder(); - tripBuilder - .addStep(mSteps.get(0), stepTravelEstimate) - .addDestination( - mDestinations.get(0), - destinationTravelEstimate) - .setLoading(false); - - if (instruction.getShouldShowNextStep() - && nextInstruction != null && mSteps.size() > 1) { - Step nextStep = mSteps.get(1); - TravelEstimate nextStepTravelEstimate = - nextInstruction.getStepTravelEstimate(); - if (nextStepTravelEstimate != null) { - tripBuilder.addStep(nextStep, - nextStepTravelEstimate); - } - } - - String road = instruction.getRoad(); - if (road != null) { - tripBuilder.setCurrentRoad(road); - } - mNavigationManager.updateTrip(tripBuilder.build()); - - if (++mStepsSent % 10 == 0) { - // For demo purposes only play audio of next turn every - // 10 steps. - playNavigationDirection(R.raw.turn_right); - mNotificationManager.notify( - NOTIFICATION_ID, - getTrafficAccidentWarningNotification()); - } - - update( - /* isNavigating= */ true, - /* isRerouting= */ false, - /* hasArrived= */ false, - mDestinations, - mSteps, - destinationTravelEstimate, - instruction.getStepRemainingDistance(), - instruction.getShouldNotify(), - instruction.getNotificationTitle(), - instruction.getNotificationContent(), - instruction.getNotificationIcon(), - instruction.getShouldShowNextStep(), - instruction.getShouldShowLanes(), - instruction.getJunctionImage()); - } - break; - case SET_REROUTING: - if (mIsNavigating) { - TravelEstimate destinationTravelEstimate = - instruction.getDestinationTravelEstimate(); - Trip.Builder tripBuilder = new Trip.Builder(); - tripBuilder - .addDestination( - mDestinations.get(0), - destinationTravelEstimate) - .setLoading(true); - mNavigationManager.updateTrip(tripBuilder.build()); - update( - /* isNavigating= */ true, - /* isRerouting= */ true, - /* hasArrived= */ false, - null, - null, - null, - null, - instruction.getShouldNotify(), - instruction.getNotificationTitle(), - instruction.getNotificationContent(), - instruction.getNotificationIcon(), - instruction.getShouldShowNextStep(), - instruction.getShouldShowLanes(), - instruction.getJunctionImage()); - } - break; - case SET_ARRIVED: - if (mIsNavigating) { - update( - /* isNavigating= */ true, - /* isRerouting= */ false, - /* hasArrived= */ true, - mDestinations, - null, - null, - null, - instruction.getShouldNotify(), - instruction.getNotificationTitle(), - instruction.getNotificationContent(), - instruction.getNotificationIcon(), - instruction.getShouldShowNextStep(), - instruction.getShouldShowLanes(), - instruction.getJunctionImage()); - } - break; - } - }); - } - - void update( - boolean isNavigating, - boolean isRerouting, - boolean hasArrived, - List destinations, - List steps, - TravelEstimate nextDestinationTravelEstimate, - Distance nextStepRemainingDistance, - boolean shouldNotify, - @Nullable String notificationTitle, - @Nullable String notificationContent, - int notificationIcon, - boolean shouldShowNextStep, - boolean shouldShowLanes, - @Nullable CarIcon junctionImage) { - if (mListener != null) { - mListener.navigationStateChanged( - isNavigating, - isRerouting, - hasArrived, - destinations, - steps, - nextDestinationTravelEstimate, - nextStepRemainingDistance, - shouldShowNextStep, - shouldShowLanes, - junctionImage); - } - - if (mNotificationManager != null && !TextUtils.isEmpty(notificationTitle)) { - mNotificationManager.notify( - NAV_NOTIFICATION_ID, - getNotification( - shouldNotify, - true, - notificationTitle, - notificationContent, - notificationIcon)); - } - } - - public boolean getIsNavigating() { - return mIsNavigating; - } - - /** Starts navigation. */ - public void startNavigation() { - Log.i(TAG, "Starting Navigation"); - startService(new Intent(getApplicationContext(), NavigationService.class)); - - Log.i(TAG, "Starting foreground service"); - startForeground( - NAV_NOTIFICATION_ID, - getNotification( - true, - false, - getString(R.string.navigation_active), - null, - R.drawable.ic_launcher)); - - if (mNavigationManager != null) { - mNavigationManager.navigationStarted(); - mIsNavigating = true; - mListener.navigationStateChanged( - mIsNavigating, - /* isRerouting= */ true, - /* hasArrived= */ false, - /* destinations= */ null, - /* steps= */ null, - /* nextDestinationTravelEstimate= */ null, - /* nextStepRemainingDistance= */ null, - /* shouldShowNextStep= */ false, - /* shouldShowLanes= */ false, - /* junctionImage= */ null); - } - } - - /** Stops navigation. */ - @SuppressWarnings("deprecation") - public void stopNavigation() { - Log.i(TAG, "Stopping Navigation"); - if (mScript != null) { - mScript.stop(); - mDestinations.clear(); - mSteps.clear(); - mScript = null; - } - - if (mNavigationManager != null) { - mNavigationManager.navigationEnded(); - mIsNavigating = false; - mListener.navigationStateChanged( - mIsNavigating, - /* isRerouting= */ false, - /* hasArrived= */ false, - /* destinations= */ null, - /* steps= */ null, - /* nextDestinationTravelEstimate= */ null, - /* nextStepRemainingDistance= */ null, - /* shouldShowNextStep= */ false, - /* shouldShowLanes= */ false, - /* junctionImage= */ null); - } - stopForeground(true); - stopSelf(); - } - - private void playNavigationDirection(@RawRes int resourceId) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { - return; - } - CarContext carContext = mCarContext; - if (carContext == null) { - return; - } - - MediaPlayer mediaPlayer = new MediaPlayer(); - - // Use USAGE_ASSISTANCE_NAVIGATION_GUIDANCE as the usage type for any navigation related - // audio, so that the audio will be played in the car speaker. - AudioAttributes audioAttributes = - new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) - .setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE) - .build(); - - mediaPlayer.setAudioAttributes(audioAttributes); - - // Request audio focus with AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK so that it will duck ongoing - // media. - // Ducking will behave differently depending on what is playing, if it is music it will - // lower - // the volume, if it is speech, it will pause it. - AudioFocusRequest request = - new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK) - .setAudioAttributes(audioAttributes) - .build(); - - AudioManager audioManager = carContext.getSystemService(AudioManager.class); - - mediaPlayer.setOnCompletionListener( - player -> { - try { - // When the audio finishes playing: stop and release the media player. - player.stop(); - player.release(); - } finally { - // Release the audio focus so that any previously playing audio can - // continue. - audioManager.abandonAudioFocusRequest(request); - } - }); - - // Requesting the audio focus. - if (audioManager.requestAudioFocus(request) != AUDIOFOCUS_REQUEST_GRANTED) { - // If audio focus is not granted ignore it. - return; - } - - try { - // Load our raw resource file, in the case where you synthesize the audio for the given - // direction, just use that audio file. - AssetFileDescriptor afd = carContext.getResources().openRawResourceFd(resourceId); - mediaPlayer.setDataSource( - afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); - afd.close(); - - mediaPlayer.prepare(); - } catch (IOException e) { - Log.e(TAG, "Failure loading audio resource", e); - // Release the audio focus so that any previously playing audio can continue. - audioManager.abandonAudioFocusRequest(request); - } - - // Start the audio playback. - mediaPlayer.start(); - } - - private void endNavigationFromScript() { - stopNavigation(); - } - - private void createNotificationChannel() { - mNotificationManager = getSystemService(NotificationManager.class); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - CharSequence name = getString(R.string.app_name); - NotificationChannel serviceChannel = - new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH); - mNotificationManager.createNotificationChannel(serviceChannel); - } - } - - /** Returns the {@link NotificationCompat} used as part of the foreground service. */ - private Notification getNotification( - boolean shouldNotify, - boolean showInCar, - CharSequence navigatingDisplayTitle, - CharSequence navigatingDisplayContent, - int notificationIcon) { - NotificationCompat.Builder builder = - new NotificationCompat.Builder(this, CHANNEL_ID) - .setContentIntent(createMainActivityPendingIntent()) - .setContentTitle(navigatingDisplayTitle) - .setContentText(navigatingDisplayContent) - .setOngoing(true) - .setCategory(NotificationCompat.CATEGORY_NAVIGATION) - .setOnlyAlertOnce(!shouldNotify) - - // Set the notification's background color on the car screen. - .setColor( - getResources().getColor(R.color.nav_notification_background_color, - null)) - .setColorized(true) - .setSmallIcon(R.drawable.ic_launcher) - .setLargeIcon( - BitmapFactory.decodeResource(getResources(), notificationIcon)) - .setTicker(navigatingDisplayTitle) - .setWhen(System.currentTimeMillis()); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - builder.setChannelId(CHANNEL_ID); - builder.setPriority(NotificationManager.IMPORTANCE_HIGH); - } - if (showInCar) { - Intent intent = new Intent(Intent.ACTION_VIEW) - .setComponent(new ComponentName(this, NavigationCarAppService.class)) - .setData(NavigationCarAppService.createDeepLinkUri(Intent.ACTION_VIEW)); - builder.extend( - new CarAppExtender.Builder() - .setImportance(NotificationManagerCompat.IMPORTANCE_HIGH) - .setContentIntent( - CarPendingIntent.getCarApp(this, intent.hashCode(), - intent, - 0)) - .build()); - } - return builder.build(); - } - - private Notification getTrafficAccidentWarningNotification() { - return new NotificationCompat.Builder(this, CHANNEL_ID) - .setContentTitle("Traffic accident ahead") - .setContentText("Drive slowly") - .setSmallIcon(R.drawable.ic_settings) - .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_settings)) - .extend( - new CarAppExtender.Builder() - .setImportance(NotificationManagerCompat.IMPORTANCE_HIGH) - .build()) - .build(); - } - - private PendingIntent createMainActivityPendingIntent() { - Intent intent = new Intent(this, MainActivity.class); - intent.putExtra(EXTRA_STARTED_FROM_NOTIFICATION, true); - return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); - } -} diff --git a/car_app_library/navigation/mobile/.gitignore b/car_app_library/navigation/mobile/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/navigation/mobile/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/navigation/mobile/build.gradle b/car_app_library/navigation/mobile/build.gradle deleted file mode 100644 index 6a5c6d7..0000000 --- a/car_app_library/navigation/mobile/build.gradle +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2021 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 - * - * http://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. - */ - -apply plugin: 'com.android.application' - -android { - compileSdk 33 - - defaultConfig { - applicationId "androidx.car.app.sample.navigation" - minSdkVersion 23 - targetSdkVersion 33 - // Increment this to generate signed builds for uploading to Playstore - // Make sure this is different from the navigation-automotive version - versionCode 114 - versionName "114" - } - - buildTypes { - release { - // Enables code shrinking, obfuscation, and optimization. - minifyEnabled true - proguardFiles getDefaultProguardFile( - 'proguard-android-optimize.txt'), - 'proguard-rules.pro' - } - } - - compileOptions { - targetCompatibility = JavaVersion.VERSION_1_8 - sourceCompatibility = JavaVersion.VERSION_1_8 - } - namespace "androidx.car.app.sample.navigation" -} - -dependencies { - implementation "androidx.car.app:app-projected:1.3.0-beta01" - implementation project(":navigation:common") -} diff --git a/car_app_library/navigation/mobile/build.gradle.kts b/car_app_library/navigation/mobile/build.gradle.kts new file mode 100644 index 0000000..10ec33e --- /dev/null +++ b/car_app_library/navigation/mobile/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + kotlin("android") + id("android-application-module") +} + +android { + namespace = "androidx.car.app.sample.navigation" + defaultConfig { + applicationId = "androidx.car.app.sample.navigation" + } +} + +dependencies { + implementation(libs.androidx.car.projected) + implementation(project(":car_app_library:navigation:shared")) + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + } \ No newline at end of file diff --git a/car_app_library/navigation/shared/.gitignore b/car_app_library/navigation/shared/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/car_app_library/navigation/shared/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/car_app_library/navigation/shared/build.gradle.kts b/car_app_library/navigation/shared/build.gradle.kts new file mode 100644 index 0000000..260e077 --- /dev/null +++ b/car_app_library/navigation/shared/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { +// kotlin("android") + id("android-library-module") +} + +android { + namespace = "androidx.car.app.sample.navigation.common" +} + +dependencies { + implementation( libs.androidx.core) + implementation( libs.androidx.car.app) + + implementation( libs.androidx.constraintlayout) +// implementation "androidx.annotation:annotation-experimental:1.0.0" +} \ No newline at end of file diff --git a/car_app_library/navigation/common/src/main/AndroidManifest.xml b/car_app_library/navigation/shared/src/main/AndroidManifest.xml similarity index 100% rename from car_app_library/navigation/common/src/main/AndroidManifest.xml rename to car_app_library/navigation/shared/src/main/AndroidManifest.xml diff --git a/car_app_library/navigation/shared/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.kt b/car_app_library/navigation/shared/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.kt new file mode 100644 index 0000000..36c200f --- /dev/null +++ b/car_app_library/navigation/shared/src/main/java/androidx/car/app/sample/navigation/common/app/MainActivity.kt @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2021 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 + * + * http://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 androidx.car.app.sample.navigation.common.app + +import android.Manifest +import android.content.ComponentName +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.IBinder +import android.util.Log +import android.view.View +import android.widget.Button +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.car.app.connection.CarConnection +import androidx.car.app.sample.navigation.common.R +import androidx.car.app.sample.navigation.common.nav.NavigationService +import androidx.car.app.sample.navigation.common.nav.NavigationService.LocalBinder + +/** + * The main app activity. + * + * + * See [androidx.car.app.sample.navigation.common.car.NavigationCarAppService] for the + * app's entry point to the cat host. + */ +class MainActivity : ComponentActivity() { + // A reference to the navigation service used to get location updates and routing. + var mService: NavigationService? = null + + // Tracks the bound state of the navigation service. + var mIsBound: Boolean = false + + // Monitors the state of the connection to the navigation service. + private val mServiceConnection: ServiceConnection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + Log.i(TAG, "In onServiceConnected() component:$name") + val binder = service as LocalBinder + mService = binder.service + mIsBound = true + } + + override fun onServiceDisconnected(name: ComponentName) { + Log.i(TAG, "In onServiceDisconnected() component:$name") + mService = null + mIsBound = false + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + Log.i(TAG, "In onCreate()") + + setContentView(R.layout.activity_main) + + // Hook up some manual navigation controls. + val startNavButton = findViewById