From 105b3c56c3bfe8c1d90d5d394d48eb76a6085f3c Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Tue, 3 Nov 2026 19:47:58 +0100 Subject: [PATCH 1/4] Add Organic Maps Android SDK samples Provide independently installable map, offline-search and routing apps. Keep asynchronous SDK readiness in the application, forward map, compass and foreground location lifecycle, and handle permission/provider results. Preserve search scrolling and native indexes across filtered snapshots, keep download feedback separate, reject stale callbacks, and retain route planning across recreation. Complete foreground navigation on arrival. Add focused lifecycle, provider-resolution, gesture and search regressions. Document a fetchable SDK revision and isolated local publication workflow. Related: organicmaps/organicmaps#5324, organicmaps/organicmaps#14102 Signed-off-by: Alexander Borsuk --- .editorconfig | 13 + .gitignore | 10 + README.md | 71 ++++ app/build.gradle.kts | 88 +++++ app/src/androidTest/AndroidManifest.xml | 8 + .../example/LocationResolutionTest.kt | 101 ++++++ .../organicmaps/example/MapLifecycleTest.kt | 50 +++ .../organicmaps/example/SampleTestSupport.kt | 50 +++ .../organicmaps/example/OfflineSearchTest.kt | 235 ++++++++++++ .../example/RoutingLifecycleTest.kt | 97 +++++ app/src/main/AndroidManifest.xml | 24 ++ .../organicmaps/example/ExampleApplication.kt | 33 ++ .../app/organicmaps/example/MainActivity.kt | 329 +++++++++++++++++ .../example/OfflineSearchActivity.kt | 202 +++++++++++ .../organicmaps/example/RoutingActivity.kt | 340 ++++++++++++++++++ .../app/organicmaps/example/SampleControls.kt | 36 ++ .../res/drawable/ic_launcher_foreground.xml | 16 + .../res/drawable/ic_location_searching.xml | 11 + app/src/main/res/drawable/ic_my_location.xml | 11 + app/src/main/res/drawable/ic_zoom_in.xml | 11 + app/src/main/res/drawable/ic_zoom_out.xml | 11 + app/src/main/res/layout/activity_main.xml | 62 ++++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + app/src/main/res/mipmap/ic_launcher.xml | 20 ++ app/src/main/res/values/colors.xml | 4 + app/src/main/res/values/dimens.xml | 4 + app/src/main/res/values/ids.xml | 14 + app/src/main/res/values/strings.xml | 63 ++++ app/src/main/res/values/themes.xml | 4 + build.gradle.kts | 41 +++ gradle.properties | 10 + gradle/libs.versions.toml | 19 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48462 bytes gradle/wrapper/gradle-wrapper.properties | 10 + gradlew | 248 +++++++++++++ gradlew.bat | 82 +++++ settings.gradle.kts | 28 ++ 37 files changed, 2361 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 README.md create mode 100644 app/build.gradle.kts create mode 100644 app/src/androidTest/AndroidManifest.xml create mode 100644 app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt create mode 100644 app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt create mode 100644 app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt create mode 100644 app/src/androidTestOffline/java/app/organicmaps/example/OfflineSearchTest.kt create mode 100644 app/src/androidTestRouting/java/app/organicmaps/example/RoutingLifecycleTest.kt create mode 100644 app/src/main/AndroidManifest.xml create mode 100644 app/src/main/java/app/organicmaps/example/ExampleApplication.kt create mode 100644 app/src/main/java/app/organicmaps/example/MainActivity.kt create mode 100644 app/src/main/java/app/organicmaps/example/OfflineSearchActivity.kt create mode 100644 app/src/main/java/app/organicmaps/example/RoutingActivity.kt create mode 100644 app/src/main/java/app/organicmaps/example/SampleControls.kt create mode 100644 app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 app/src/main/res/drawable/ic_location_searching.xml create mode 100644 app/src/main/res/drawable/ic_my_location.xml create mode 100644 app/src/main/res/drawable/ic_zoom_in.xml create mode 100644 app/src/main/res/drawable/ic_zoom_out.xml create mode 100644 app/src/main/res/layout/activity_main.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 app/src/main/res/mipmap/ic_launcher.xml create mode 100644 app/src/main/res/values/colors.xml create mode 100644 app/src/main/res/values/dimens.xml create mode 100644 app/src/main/res/values/ids.xml create mode 100644 app/src/main/res/values/strings.xml create mode 100644 app/src/main/res/values/themes.xml create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..98af668 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*.{kt,kts}] +indent_style = space +indent_size = 4 +max_line_length = 120 +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +ktlint_code_style = android_studio +ij_kotlin_allow_trailing_comma_on_call_site = true +ij_kotlin_allow_trailing_comma = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3f31d91 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle/ +.kotlin/ +build/ +local.properties +.idea/ +.DS_Store +captures/ +.externalNativeBuild/ +.cxx/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..6b8a978 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# Organic Maps Android SDK examples + +Three independently installable Android apps demonstrate the SDK: + +| Variant | Try it | +| --- | --- | +| `basic` | Pan and zoom the map, select a place, and enable your position. | +| `offline` | Find a region such as Liechtenstein, select it, and download it. Then search installed maps for a place or category. Download and search feedback are independent. | +| `routing` | Select an origin and destination, choose walking/cycling/driving, and build a route. Download missing maps when prompted. For navigation, obtain a fix and use your position as the origin. | + +Each app has separate map storage. Route planning survives rotation and backgrounding; +foreground navigation ends on arrival, Stop, backgrounding, or closing the activity. +Downloads continue independently of the screen and offer cancellation and retry. + +The SDK API is experimental and may change. See the +[SDK integration guide](https://github.com/organicmaps/organicmaps/blob/9b5343caf0d19f1a6e06511fdac5d6f7e59a1f12/android/sdk/README.md) +for initialization, lifecycle, permissions, packaging, and API contracts. + +## Build and run + +Use **JDK 21**, **Android SDK Platform 37**, and an **API 21+** device or emulator. +The examples consume native libraries from SDK AARs and do not need an NDK. + +Until a public SDK release is available, publish its artifacts locally. The revision +below contains `publishSdkForChecks` from +[organicmaps/organicmaps#14025](https://github.com/organicmaps/organicmaps/pull/14025). +Building that checkout requires the upstream +[native build environment](https://github.com/organicmaps/organicmaps/blob/9b5343caf0d19f1a6e06511fdac5d6f7e59a1f12/docs/INSTALL.md). +With an Organic Maps checkout in the sibling `organicmaps` directory: + +```sh +git -C ../organicmaps fetch origin 9b5343caf0d19f1a6e06511fdac5d6f7e59a1f12 +git -C ../organicmaps checkout --detach FETCH_HEAD +git -C ../organicmaps submodule update --init --recursive --depth 1 +(cd ../organicmaps/android && ./gradlew -Parm64 -PsdkVersion=0.0.0-sdk-check publishSdkForChecks) +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check checkSamples +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check :app:installBasicDebug +``` + +Use `installOfflineDebug` or `installRoutingDebug` for the other samples. Keep the same +`sdkRepository` and `sdkVersion` options for every command. `-Parm64` builds SDK AARs +for arm64; use `-Px86_64` in the producer for an Intel emulator. Examples package the +ABIs supplied by those AARs. Release APKs are minified and signed with the debug key +for local installation. + +`sdkRepository` restricts the SDK group to the supplied repository. Without it, +Google, Maven Central, and `mavenLocal()` are available. Local Maven publication also +requires `-PsdkVersion=0.0.0-sdk-check` in the producer to match the default consumer +version; published releases can be selected with `-PsdkVersion=`. + +## Checks + +`checkSamples` runs Kotlin style checks and Android lint, builds all debug/minified +release APKs, and builds the instrumentation tests. Run `ktlintFormat` to format Kotlin. +On a matching connected device or emulator: + +```sh +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check connectedSamples +``` + +CI publishes the pinned SDK into an isolated repository and runs these checks on an +API 35 emulator. The manual workflow's `sdk_ref` input selects another SDK revision. +For device checks, also exercise denied/disabled location, rotation during loading, +light/dark themes, cancelled downloads, missing-map routing, and navigation arrival; +repeat with minified release APKs. + +## License and support + +See [LICENSE](LICENSE). Report sample issues in +[organicmaps/sdk-android](https://github.com/organicmaps/sdk-android/issues) and SDK or +engine issues in [organicmaps/organicmaps](https://github.com/organicmaps/organicmaps/issues). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..3068a56 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,88 @@ +plugins { + alias(libs.plugins.android.application) +} + +android { + namespace = "app.organicmaps.example" + compileSdk = providers.gradleProperty("propCompileSdkVersion").get().toInt() + + // Use the built-in Kotlin support of the Android Gradle Plugin 9+. + enableKotlin = true + + buildFeatures { + buildConfig = true + resValues = true + } + + defaultConfig { + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + applicationId = "app.organicmaps.example" + minSdk = providers.gradleProperty("propMinSdkVersion").get().toInt() + targetSdk = providers.gradleProperty("propTargetSdkVersion").get().toInt() + versionCode = 1 + versionName = "1.0" + } + + flavorDimensions += "sample" + productFlavors { + create("basic") { + dimension = "sample" + applicationIdSuffix = ".basic" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.MainActivity" + resValue("string", "app_name", "OM SDK Map") + } + create("offline") { + dimension = "sample" + applicationIdSuffix = ".offline" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.OfflineSearchActivity" + resValue("string", "app_name", "OM SDK Offline Search") + } + create("routing") { + dimension = "sample" + applicationIdSuffix = ".routing" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.RoutingActivity" + resValue("string", "app_name", "OM SDK Routing") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + // Required by the Organic Maps SDK (it is built with desugaring enabled). + isCoreLibraryDesugaringEnabled = true + } + + // The native core reads .mwm maps, fonts and packed polygons directly from + // the APK using random access, so they must be stored uncompressed. + androidResources { + noCompress += listOf("png", "mwm", "ttf", "packed_polygons.bin") + } + + buildTypes { + release { + // Minification works out of the box: the SDK ships consumer R8 rules + // that keep the classes accessed from the native code via JNI. + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) + // Sign with the debug key so the example can be installed right away. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +dependencies { + val sdkVersion = providers.gradleProperty("sdkVersion").getOrElse(libs.versions.organicmaps.sdk.get()) + // The Organic Maps SDK: rendering engine, offline maps framework, location. + implementation("app.organicmaps.sdk:sdk:$sdkVersion") + // Bundles overview maps; detailed offline search and routing still require region downloads. + implementation("app.organicmaps.sdk:maps-world:$sdkVersion") + + coreLibraryDesugaring(libs.android.tools.desugaring) + + implementation(libs.androidx.appcompat) + implementation(libs.google.material) + + androidTestImplementation(libs.androidx.test.core) + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.test.junit) +} diff --git a/app/src/androidTest/AndroidManifest.xml b/app/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000..15d60a7 --- /dev/null +++ b/app/src/androidTest/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt b/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt new file mode 100644 index 0000000..5367905 --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt @@ -0,0 +1,101 @@ +package app.organicmaps.example + +import android.app.Activity +import android.app.AppOpsManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.location.Criteria +import android.location.LocationManager +import android.os.Bundle +import android.os.ParcelFileDescriptor +import android.os.Process +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SdkSuppress +import androidx.test.platform.app.InstrumentationRegistry +import app.organicmaps.sdk.Map as OMMap +import app.organicmaps.sdk.location.LocationState +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +class LocationResolutionActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setResult(intent.getIntExtra("result", RESULT_CANCELED)) + finish() + } +} + +@RunWith(AndroidJUnit4::class) +@SdkSuppress(minSdkVersion = 23) // Per-app mock-location selection requires Android M. +class LocationResolutionTest { + private lateinit var locationManager: LocationManager + private var mockLocationMode = "default" + private var testGpsInstalled = false + + @Before + @Suppress("DEPRECATION") // The ProviderProperties overload requires API 31. + fun installTestGps() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager + val mode = appOps.checkOpNoThrow("android:mock_location", Process.myUid(), context.packageName) + mockLocationMode = listOf("allow", "ignore", "deny", "default", "foreground")[mode] + setMockLocationMode("allow") + locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager + // Resolution tests need polling state, without depending on physical fixes or the emulator's GNSS HAL. + locationManager.addTestProvider( + LocationManager.GPS_PROVIDER, false, true, false, false, true, true, true, + Criteria.POWER_LOW, Criteria.ACCURACY_FINE, + ) + testGpsInstalled = true + locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true) + } + + @After + fun removeTestGps() { + if (testGpsInstalled) locationManager.removeTestProvider(LocationManager.GPS_PROVIDER) + setMockLocationMode(mockLocationMode) + } + + private fun setMockLocationMode(mode: String) { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val command = instrumentation.uiAutomation.executeShellCommand( + "appops set ${instrumentation.targetContext.packageName} android:mock_location $mode", + ) + ParcelFileDescriptor.AutoCloseInputStream(command).use { it.readBytes() } + } + + @Test + fun acceptedResolutionRestartsLocation() = resolveLocation(Activity.RESULT_OK) + + @Test + fun cancelledResolutionKeepsLocationStopped() = resolveLocation(Activity.RESULT_CANCELED) + + private fun resolveLocation(result: Int) { + launchSample().use { scenario -> + scenario.await { OMMap.isEngineCreated() } + scenario.onActivity { activity -> + val helper = (activity.application as ExampleApplication).organicMaps.locationHelper + helper.start() + val testPackage = InstrumentationRegistry.getInstrumentation().context.packageName + val intent = Intent().setClassName(testPackage, LocationResolutionActivity::class.java.name) + .putExtra("result", result) + val resolution = PendingIntent.getActivity(activity, result, intent, PendingIntent.FLAG_IMMUTABLE) + helper.onLocationResolutionRequired(resolution) + assertFalse(helper.isActive) + } + if (result == Activity.RESULT_OK) { + scenario.await { (it.application as ExampleApplication).organicMaps.locationHelper.isActive } + } else { + scenario.await { LocationState.getMode() == LocationState.NOT_FOLLOW_NO_POSITION } + scenario.onActivity { + assertFalse((it.application as ExampleApplication).organicMaps.locationHelper.isActive) + } + } + } + } +} diff --git a/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt b/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt new file mode 100644 index 0000000..b9f77db --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt @@ -0,0 +1,50 @@ +package app.organicmaps.example + +import android.view.View +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.Lifecycle +import androidx.test.ext.junit.runners.AndroidJUnit4 +import app.organicmaps.sdk.Map as OMMap +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class MapLifecycleTest { + @Test + fun compassSubscriptionFollowsActivityVisibilityAndRecreation() { + launchSample().use { scenario -> + scenario.await { OMMap.isEngineCreated() } + scenario.await { activity -> + val button = activity.findViewById(R.id.my_position) + val insets = ViewCompat.getRootWindowInsets(button) + ?.getInsets(WindowInsetsCompat.Type.systemBars()) ?: return@await false + val position = IntArray(2) + button.getLocationOnScreen(position) + button.height > 0 && position[1] + button.height <= activity.window.decorView.height - insets.bottom + } + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertEquals(setOf(it), listeners.get(helper)) + it.onCompassUpdated(0.5) + } + scenario.moveToState(Lifecycle.State.CREATED) + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertTrue((listeners.get(helper) as Set<*>).isEmpty()) + } + scenario.moveToState(Lifecycle.State.RESUMED) + scenario.recreate() + scenario.await { OMMap.isEngineCreated() } + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertEquals(setOf(it), listeners.get(helper)) + } + } + } +} diff --git a/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt b/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt new file mode 100644 index 0000000..2a393bc --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt @@ -0,0 +1,50 @@ +package app.organicmaps.example + +import android.Manifest +import android.os.ParcelFileDescriptor +import android.os.SystemClock +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import androidx.annotation.StringRes +import androidx.test.core.app.ActivityScenario +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertTrue + +internal fun launchSample(): ActivityScenario { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + for (permission in listOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)) { + val command = instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} $permission") + ParcelFileDescriptor.AutoCloseInputStream(command).use { it.readBytes() } + } + val intent = requireNotNull(context.packageManager.getLaunchIntentForPackage(context.packageName)) + return ActivityScenario.launch(intent).also { scenario -> + scenario.await { it.findViewById(R.id.my_position)?.isShown == true } + } +} + +internal fun ActivityScenario.await(condition: (MainActivity) -> Boolean) { + val deadline = SystemClock.uptimeMillis() + 15_000 + do { + var matched = false + onActivity { matched = condition(it) } + if (matched) return + SystemClock.sleep(50) + } while (SystemClock.uptimeMillis() < deadline) + throw AssertionError("Sample did not reach the expected UI state") +} + +internal fun View.descendants(): Sequence = sequence { + yield(this@descendants) + if (this@descendants is ViewGroup) { + for (index in 0 until childCount) yieldAll(getChildAt(index).descendants()) + } +} + +internal fun MainActivity.click(@StringRes label: Int) { + val button = findViewById(R.id.sample_panel).descendants() + .filterIsInstance