1
+ package com.mapbox.maps.testapp.auto.car
2
+
3
+ import android.content.SharedPreferences
4
+ import androidx.car.app.AppManager
5
+ import androidx.lifecycle.DefaultLifecycleObserver
6
+ import androidx.lifecycle.LifecycleOwner
7
+ import com.mapbox.maps.MapboxExperimental
8
+ import com.mapbox.maps.extension.androidauto.MapboxCarMap
9
+ import com.mapbox.maps.extension.androidauto.MapboxCarMapInitializer
10
+ import com.mapbox.maps.logI
11
+ import com.mapbox.maps.testapp.auto.CarAppPreferences
12
+ import com.mapbox.maps.testapp.auto.custom.SurfaceCallbackInterceptor
13
+
14
+ /* *
15
+ * In order to enable onClick, you need to override the mapboxCarMap.prepareSurfaceCallback
16
+ *
17
+ * This class allows you to toggle the preference from the app, to show that you can change this
18
+ * setting at runtime. In real scenarios, it may be initialize the map with onClick enabled.
19
+ */
20
+ @OptIn(MapboxExperimental ::class )
21
+ class CarMapOnClickEnabler (
22
+ private val mapboxCarMap : MapboxCarMap ,
23
+ private val initializer : MapboxCarMapInitializer
24
+ ) : DefaultLifecycleObserver {
25
+
26
+ private var carAppPreferences: CarAppPreferences ? = null
27
+
28
+ private val listener = SharedPreferences .OnSharedPreferenceChangeListener { sharedPreferences, key ->
29
+ if (key == CarAppPreferences .BOOLEAN_KEY_ENABLE_ON_CLICK ) {
30
+ val customCallbackEnabled = sharedPreferences.getBoolean(key, false )
31
+ onEnableOnClickPreferenceChanged(customCallbackEnabled)
32
+ }
33
+ }
34
+
35
+ override fun onResume (owner : LifecycleOwner ) {
36
+ super .onResume(owner)
37
+ carAppPreferences = CarAppPreferences (mapboxCarMap.carContext).apply {
38
+ sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
39
+ onEnableOnClickPreferenceChanged(isOnClickEnabled())
40
+ }
41
+ }
42
+
43
+ override fun onPause (owner : LifecycleOwner ) {
44
+ super .onPause(owner)
45
+ carAppPreferences?.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(listener)
46
+ carAppPreferences = null
47
+ }
48
+
49
+ private fun onEnableOnClickPreferenceChanged (customCallbackEnabled : Boolean ) {
50
+ val carContext = mapboxCarMap.carContext
51
+ if (customCallbackEnabled) {
52
+ val surfaceCallback = mapboxCarMap.prepareSurfaceCallback(
53
+ carContext, initializer.onCreate(carContext)
54
+ )
55
+ carContext.getCarService(AppManager ::class .java)
56
+ .setSurfaceCallback(object : SurfaceCallbackInterceptor (surfaceCallback) {
57
+ override fun onClick (x : Float , y : Float ) {
58
+ super .onClick(x, y)
59
+ onMapSurfaceClick(x, y)
60
+ }
61
+ })
62
+ } else {
63
+ mapboxCarMap.setup(carContext, initializer.onCreate(carContext))
64
+ }
65
+ }
66
+
67
+ private fun onMapSurfaceClick (x : Float , y : Float ) {
68
+ logI(" CarMapOnClickEnabler" , " onMapSurfaceClick $x $y " )
69
+ }
70
+ }
0 commit comments