Page Menu
Home
GitPull.it
Search
Configure Global Search
Log In
Files
F15167964
D264.1794957736.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Authored By
Unknown
Size
47 KB
Referenced Files
None
Subscribers
None
D264.1794957736.diff
View Options
diff --git a/.gitignore b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,8 @@
# Built application files
*.apk
*.ap_
+*.dm
+*.aab
# Files for the ART/Dalvik VM
*.dex
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
@@ -646,7 +646,7 @@
messageTextView.visibility = View.VISIBLE
}
-
+ //TODO: Remove all this loader stuff
override fun onCreateLoader(id: Int, p1: Bundle?): Loader<Cursor> {
val args = arguments
//if (args?.getString(KEY_STOP_ID) == null) throw
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
@@ -65,9 +65,10 @@
import it.reyboz.bustorino.data.PreferencesHolder
import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops
import it.reyboz.bustorino.map.MapLibreLocationEngine
+import it.reyboz.bustorino.map.MapLibreStyles
import it.reyboz.bustorino.map.MapLibreUtils
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.util.ViewUtils
import it.reyboz.bustorino.viewmodels.LivePositionsViewModel
import it.reyboz.bustorino.viewmodels.MapStateViewModel
@@ -159,7 +160,7 @@
if(mMap == null){
Log.w(DEBUG_TAG, "Location request completed, but map is null!")
}else{
- initializeMapLocationComponent(mMap,requireContext(), null)
+ initializeMapLocationComponent(mMap,requireContext(), mMap.style!!)
}
} else{
// PERMISSION DENIED
@@ -180,7 +181,7 @@
protected lateinit var arrivalsCard: CardView
protected lateinit var directionsCard: CardView
protected lateinit var bottomrightImage: ImageView
- protected lateinit var locationComponent: LocationComponent
+ protected var locationComponent: LocationComponent? = null
protected lateinit var busPositionsIconButton: ImageButton
protected lateinit var vehicleIcon: ImageView
protected lateinit var warningTripIcon: ImageView
@@ -366,22 +367,52 @@
}
}
- protected fun reloadMap(){
- /*map?.let {
- Log.d("GeneralMapFragment", "RELOADING MAP")
- //save map state
- savedMapStateOnPause = saveMapStateInBundle()
-
- onMapDestroy()
- //Destroy and recreate MAP
- mapView.onDestroy()
- mapView.onCreate(null)
- mapView.getMapAsync(this)
+ override fun onMapReady(mapReady: MapLibreMap) {
+ this.map = mapReady
+ val context = requireContext()
+
+ // 1. Caricamento Stile (Comune)
+ val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context))
+ val builder = Style.Builder().fromJson(mjson!!)
+
+ mapReady.setStyle(builder) { style ->
+ mapStyle = style
+ addImagesStyle(style)
+
+ // Gancio per layer e configurazioni specifiche dello stile
+ onStyleLoaded(mapReady, style)
+
+ checkInitMapLocation(mapReady, style, context)
}
- */
+ // 2. Setup Listeners (Comune + Specifici)
+ setupMapListenersOnInit(mapReady)
+
+ // 4. Ripristino Camera / observe Buses
+
+ mapInitialized = true
+ mapStateViewModel.mapInitOnce.set(true)
+
+ onMapLibreInitialized(mapReady)
+
}
+ // --- Methods to implement in subclasses ---
+ /**
+ * Called when the map is loaded and the style is ready
+ */
+ abstract fun onStyleLoaded(mapReady: MapLibreMap,style: Style)
+
+ /**
+ * Called during the init setup of the map, separate method to add listeners to the map
+ */
+ abstract fun setupMapListenersOnInit(mapReady: MapLibreMap)
+
+ /**
+ * All things to do on the map different from listeners: listen to bus stops, bus positions updates...
+ */
+ abstract fun onMapLibreInitialized(mapReady: MapLibreMap)
+
//For extra stuff to do when the map is destroyed
abstract fun onMapDestroy()
@@ -499,37 +530,39 @@
return changed
}
+ /**
+ * Method to be called to start all the location stuff related to the map
+ * ONLY WHEN YOU HAVE THE LOCATION PERMISSION
+ */
@SuppressLint("MissingPermission")
- protected fun initializeMapLocationComponent(map: MapLibreMap, context: Context, style: Style?){
- val mStyle = style ?: map.style
+ protected fun initializeMapLocationComponent(map: MapLibreMap, context: Context, style: Style){
if(locationInitialized){
Log.w(DEBUG_TAG, "trying to initialize Location Component, but it is already done")
return
}
- mStyle?.let{ style ->
- locationComponent = map.locationComponent
-
- val locProvider = FusedNativeLocationProvider(context)
- locProvider.addListener(deviceLocationStatusListener)
- locationEngine = MapLibreLocationEngine(locProvider)
- locationProvider = locProvider
- val options = LocationComponentActivationOptions.builder(context, style)
- .useDefaultLocationEngine(false)
- .locationEngine(locationEngine)
- .build()
- locationComponent.activateLocationComponent(options)
-
- if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Initializing location, request initial position")
- startInitialPositionRequest()
-
- if(!locationEnabledOnDevice){
- warnLocationNotEnabledOnDevice()
- }else {
- setLocationComponentEnabled(true)
- }
- locationInitialized = true
- onMapLocationComponentInitialized()
+ locationComponent = map.locationComponent
+
+ val locProvider = FusedNativeLocationProvider(context)
+ locProvider.addListener(deviceLocationStatusListener)
+ locationEngine = MapLibreLocationEngine(locProvider)
+ locationProvider = locProvider
+ val options = LocationComponentActivationOptions.builder(context, style)
+ .useDefaultLocationEngine(false)
+ .locationEngine(locationEngine)
+ .build()
+ locationComponent!!.activateLocationComponent(options)
+
+ if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Initializing location, request initial position")
+ startInitialPositionRequest()
+
+ if(!locationEnabledOnDevice){
+ warnLocationNotEnabledOnDevice()
+ }else {
+ setLocationComponentEnabled(true)
}
+ locationInitialized = true
+ onMapLocationComponentInitialized()
+
}
@SuppressLint("MissingPermission")
@@ -1089,35 +1122,38 @@
/**
* Method used for enabling / disabling the location from the buttons
*/
- protected fun switchUserLocationStatus(view: View?){
- val enabled = if(locationInitialized) locationComponent.isLocationComponentEnabled else false
+ protected fun switchUserLocationStatus(view: View?) {
+
+ val enabled = locationInitialized && (locationComponent?.isLocationComponentEnabled == true)
val context = context ?: return
- if(enabled) {
- if(!receivedFirstLocation){
+ if (enabled) {
+ if (!receivedFirstLocation) {
//use case: the user has decided to disable the location before the first position arrived
stopInitialPositionRequest()
}
// we have to disable it
setMapLocationEnabled(false)
- }
- else if(deviceHasLocationProvider()) {
- if(Permissions.bothLocationPermissionsGranted(context)){
- if(!locationEnabledOnDevice){
+ } else if (deviceHasLocationProvider()) {
+ if (PermissionsHelper.bothLocationPermissionsGranted(context)) {
+ if (!locationEnabledOnDevice) {
warnLocationNotEnabledOnDevice()
- } else{
+ } else {
setMapLocationEnabled(true)
}
- } else{
+ } else {
Log.d(DEBUG_TAG, "Requesting permissions to show location")
- Permissions.getInstance(context).checkRequestLocationPermissions(requireActivity(), positionRequestResponder)
+ PermissionsHelper.getInstance(context)
+ .checkRequestLocationPermissions(requireActivity(), positionRequestResponder)
}
- } else{
+ } else {
context.let {
Toast.makeText(it, R.string.no_gps_on_device, Toast.LENGTH_SHORT).show()
}
- //adjust ui
- setLocationIconEnabled(false)
- }
+ mapStateViewModel.locationUserActive.value = false
+ //adjust ui - done in response to the above
+ //setLocationIconEnabled(false)
+
+ }
}
@@ -1127,29 +1163,32 @@
@SuppressLint("MissingPermission")
protected fun setMapLocationEnabled(enabled: Boolean){
Log.d(DEBUG_TAG, "Setting map location enabled: $enabled")
- map?.locationComponent?.isLocationComponentEnabled = enabled
- //map?.cameraPosition =
+ val locCompo = map?.locationComponent
+ if (locCompo!=null)
+ locCompo.isLocationComponentEnabled = enabled
+ else Log.w(DEBUG_TAG, "Asked to set location to $enabled but locationComponent is null")
+
mapStateViewModel.locationUserActive.value = enabled
onMapLocationEnabled(enabled)
}
/**
- * Function to run at the first time the fragment is opened
+ * Function to run at the first time the map is ready
* Check if we have the permissions, and then initialize the map location component
* If we don't have it, request the permission
*/
protected fun checkInitMapLocation(mapReady: MapLibreMap,style: Style, context: Context) {
//enable location
val hasGps = deviceHasLocationProvider()
- val permissions = Permissions.getInstance(context)
+ val permissionsHelper = PermissionsHelper.getInstance(context)
if(hasGps) {
- if (Permissions.bothLocationPermissionsGranted(context)) {
+ if (PermissionsHelper.bothLocationPermissionsGranted(context)) {
Log.d(DEBUG_TAG, "Have got the location permission, init location component")
initializeMapLocationComponent(mapReady, context, style)
}else {
var req = false
activity?.let{
- req = permissions.checkRequestLocationPermissions(it, positionRequestResponder)
+ req = permissionsHelper.checkRequestLocationPermissions(it, positionRequestResponder)
}
if(!req) {
@@ -1157,7 +1196,10 @@
}
}
+ } else{
+ mapStateViewModel.setLocationNotAvailable()
}
+
}
/**
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
@@ -30,11 +30,10 @@
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
-import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import it.reyboz.bustorino.R
import it.reyboz.bustorino.backend.utils
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.util.ViewUtils
import java.lang.IllegalStateException
@@ -52,7 +51,7 @@
private val locationRequestResLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){ res ->
//onActivityResult(res: map<String,Boolean>)
- if(res[Permissions.LOCATION_PERMISSIONS[0]] ==true || res[Permissions.LOCATION_PERMISSIONS[1]] ==true)
+ if(res[PermissionsHelper.LOCATION_PERMISSIONS[0]] ==true || res[PermissionsHelper.LOCATION_PERMISSIONS[1]] ==true)
setInteractButtonState(ButtonState.LOCATION,false)
}
private val notificationsReqLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
@@ -107,11 +106,11 @@
textView.text = utils.convertHtml(getString(R.string.tutorial_map))
if (Build.VERSION.SDK_INT >= 23) {
//only show if running on Android M or above
- val permGranted = (Permissions.anyLocationPermissionsGranted(requireContext()))
+ val permGranted = (PermissionsHelper.anyLocationPermissionsGranted(requireContext()))
setInteractButtonState(ButtonState.LOCATION, !permGranted)
interactButton.setOnClickListener {
//ask location permission
- Permissions.getInstance(requireContext()).checkRequestLocationPermissions(requireActivity(), locationRequestResLauncher)
+ PermissionsHelper.getInstance(requireContext()).checkRequestLocationPermissions(requireActivity(), locationRequestResLauncher)
//locationRequestResLauncher.launch(Permissions.LOCATION_PERMISSIONS)
}
interactButton.visibility = View.VISIBLE
@@ -126,7 +125,7 @@
setImageBitmap(imageHolder,R.drawable.tuto_menu)
setTextHtmlDescription(R.string.tutorial_menu)
//this is the cheapest trick ever lol
- if(!Permissions.isNotificationPermissionNeeded()){
+ if(!PermissionsHelper.isNotificationPermissionNeeded()){
//no other screen needed
val button = root.findViewById<Button>(R.id.closeAllButton)
button.visibility = View.VISIBLE
@@ -139,14 +138,14 @@
7 ->{
imageHolder.setImageDrawable(ContextCompat.getDrawable(requireContext(),R.drawable.megaphone))
setTextHtmlDescription(R.string.tutorial_permissions)
- if(Permissions.isNotificationPermissionNeeded()) {
- val disabled = Permissions.isPermissionGranted(
+ if(PermissionsHelper.isNotificationPermissionNeeded()) {
+ val disabled = PermissionsHelper.isPermissionGranted(
requireContext(),
android.Manifest.permission.POST_NOTIFICATIONS
)
setInteractButtonState(ButtonState.NOTIFICATIONS, !disabled)
interactButton.setOnClickListener {
- if (Permissions.isNotificationPermissionNeeded()) {
+ if (PermissionsHelper.isNotificationPermissionNeeded()) {
notificationsReqLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
}
}
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt
@@ -18,7 +18,6 @@
package it.reyboz.bustorino.fragments
-import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
@@ -50,7 +49,7 @@
import it.reyboz.bustorino.data.PreferencesHolder
import it.reyboz.bustorino.data.gtfs.MatoPatternWithStops
import it.reyboz.bustorino.map.*
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.viewmodels.LinesViewModel
import it.reyboz.bustorino.viewmodels.MapStateViewModel
import it.reyboz.bustorino.viewmodels.ServiceAlertsViewModel
@@ -81,13 +80,7 @@
private var patternsAdapter: ArrayAdapter<String>? = null
- //private var isBottomSheetShowing = false
- private var shouldMapLocationBeReactivated = true
-
private var toRunWhenMapReady : Runnable? = null
- //private var mapInitialized = AtomicBoolean(false)
-
- //private var patternsSpinnerState: Parcelable? = null
private lateinit var currentPatterns: List<MatoPatternWithStops>
@@ -168,15 +161,8 @@
//style and sources are in GeneralMapLibreFragment
private lateinit var polylineSource: GeoJsonSource
private lateinit var polyArrowSource: GeoJsonSource
-
- private var savedCameraPosition: CameraPosition? = null
-
private var lastStopsSizeShown = 0
-
//BUS POSITIONS
-
- private var enablingPositionFromClick = false
-
private var polyline: LineString? = null
//private var stopPosList = ArrayList<GeoPoint>()
@@ -184,14 +170,10 @@
//fragment actions
private var showOnTopOfLine = false
- private var recyclerInitDone = false
private var usingMQTTPositions = true
private var restoredCameraInMap = false
- //position of live markers
-
- private val tripMarkersAnimators = HashMap<String, ObjectAnimator>()
//extra items to use the LibreMap
@@ -413,6 +395,7 @@
descripTextView.visibility = View.VISIBLE
}
mapStateViewModel.locationUserActive.observe(viewLifecycleOwner) {
+ Log.d(DEBUG_TAG, "User location is enabled: $it")
setLocationIconEnabled(it)
}
// enable info button if there are alerts on the line
@@ -446,11 +429,19 @@
hideStopOrBusBottomSheet()
- if(locationComponent.isLocationComponentEnabled){
+ if(locationComponent?.isLocationComponentEnabled == true){
+ //disable location
+ setLocationComponentEnabled(false)
+ //shouldMapLocationBeReactivated = true
+ } //else
+ //shouldMapLocationBeReactivated = false
+
+ /*if(mapStateViewModel.locationUserActive.value == true) {
setLocationComponentEnabled(false)
shouldMapLocationBeReactivated = true
- } else
- shouldMapLocationBeReactivated = false
+ } else shouldMapLocationBeReactivated = false
+
+ */
}
private fun hideStopListAndShowMap(){
@@ -470,8 +461,10 @@
switchButton.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_list_30))
- if(shouldMapLocationBeReactivated){
- setLocationComponentEnabled(Permissions.bothLocationPermissionsGranted(requireContext()))
+ if(mapStateViewModel.locationUserActive.value == true){
+ val actual = (PermissionsHelper.bothLocationPermissionsGranted(requireContext()))
+ setLocationComponentEnabled(actual)
+ if (!actual) context?.let{ Toast.makeText(it, R.string.location_permission_not_granted, Toast.LENGTH_LONG).show() }
}
}
@@ -520,114 +513,93 @@
}
// ------------- Map Code -------------------------
- /**
- * This method sets up the map and the layers
- */
- override fun onMapReady(mapReady: MapLibreMap) {
- this.map = mapReady
- var setViewAlready = false
-
- val context = requireContext()
- val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context)) //ViewUtils.loadJsonFromAsset(requireContext(),"map_style_good.json")
-
- activity?.run {
- val builder = Style.Builder().fromJson(mjson!!)
-
- mapReady.setStyle(builder) { style ->
- addImagesStyle(style)
-
- mapStyle = style
- //setupLayers(style)
-
- //checkInitMapLocation(mapReady, style,requireContext())
- //if(!stopsLayerStarted)
- initPolylineStopsLayers(style, null)
+ override fun onStyleLoaded(mapReady: MapLibreMap, style: Style) {
- setupBusLayer(style)
+ initPolylineStopsLayers(style, null)
- initSymbolManager(mapReady, style)
- toRunWhenMapReady?.run()
- toRunWhenMapReady = null
- mapInitialized = true
+ setupBusLayer(style)
- if(patternShown!=null){
- viewModel.stopsForPatternLiveData.value?.let {
- Log.d(DEBUG_TAG, "Show stops from the cache")
- displayPatternWithStopsOnMap(patternShown!!, it, true)
- //Show stop from cache
- mapStateViewModel.lastOpenStopID.value?.let{ sID->
- val s= it.filter { stop -> stop.ID==sID }
- if (s.isEmpty()) {
- if(sID.isNotEmpty())
- Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
- }
- else openStopInBottomSheet(s[0])
+ initSymbolManager(mapReady, style)
+ if(!mapStateViewModel.mapInitOnce.get() || mapStateViewModel.locationUserActive.value == true)
+ checkInitMapLocation(mapReady, style, requireContext())
+ }
- }
+ override fun setupMapListenersOnInit(mapReady: MapLibreMap) {
+ mapReady.addOnMapClickListener { point ->
+ val screenPoint = mapReady.projection.toScreenLocation(point)
+ val stopsNearby = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID)
+ val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID)
+ //Log.d(DEBUG_TAG, "onMapClick, stopsNearby: $stopsNearby \nstopShown: $shownStopInBottomSheet \nbusNearby: $busNearby,")
+
+ if (stopsNearby.isNotEmpty()) {
+ val feature = stopsNearby[0]
+ val id = feature.getStringProperty("id")
+ val stop = viewModel.getStopByID(id)
+ stop?.let {
+ if (isBottomSheetShowing()) {
+ hideStopOrBusBottomSheet()
}
+ openStopInBottomSheet(it)
-
+ //move camera
+ if(it.latitude!=null && it.longitude!=null)
+ mapReady.animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude!!,it.longitude!!)),750)
}
- var restoredMapState = mapStateViewModel.restoreMapState(mapReady)
- arguments?.let { args ->
- // if there is a Camera State in the arguments, set it for the new camera (doesn't work yet!)
- if (!restoredMapState && MapCameraState.checkInBundle(args)) {
- val initCamState = MapCameraState.fromBundle(args)
- //map?.let{
- MapStateViewModel.restoreMapState(mapReady, initCamState)
- setViewAlready = true
- restoredMapState = true
+ return@addOnMapClickListener true
+ } else if (busNearby.isNotEmpty()){
+ val feature = busNearby[0]
+ openBusFromMapClick(feature)
- }
- }
- restoredCameraInMap = restoredMapState
+ return@addOnMapClickListener true
}
+ false
+ }
+ }
- mapReady.addOnMapClickListener { point ->
- val screenPoint = mapReady.projection.toScreenLocation(point)
- val stopsNearby = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID)
- val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID)
- //Log.d(DEBUG_TAG, "onMapClick, stopsNearby: $stopsNearby \nstopShown: $shownStopInBottomSheet \nbusNearby: $busNearby,")
-
- if (stopsNearby.isNotEmpty()) {
- val feature = stopsNearby[0]
- val id = feature.getStringProperty("id")
- val stop = viewModel.getStopByID(id)
- stop?.let {
- if (isBottomSheetShowing()) {
- hideStopOrBusBottomSheet()
- }
- openStopInBottomSheet(it)
+ override fun onMapLibreInitialized(mapReady: MapLibreMap) {
+ toRunWhenMapReady?.run()
+ toRunWhenMapReady = null
- //move camera
- if(it.latitude!=null && it.longitude!=null)
- mapReady.animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude!!,it.longitude!!)),750)
- }
- return@addOnMapClickListener true
- } else if (busNearby.isNotEmpty()){
- val feature = busNearby[0]
- openBusFromMapClick(feature)
+ observeBusPositionUpdates()
+
+ if(patternShown!=null){
+ viewModel.stopsForPatternLiveData.value?.let {
+ Log.d(DEBUG_TAG, "Show stops from the cache")
+ displayPatternWithStopsOnMap(patternShown!!, it, true)
+ //Show stop from cache
+ mapStateViewModel.lastOpenStopID.value?.let { sID ->
+ val s = it.filter { stop -> stop.ID == sID }
+ if (s.isEmpty()) {
+ if (sID.isNotEmpty())
+ Log.w(DEBUG_TAG, "Wanted to open stop $sID in map but it was not loaded!")
+ } else openStopInBottomSheet(s[0])
- return@addOnMapClickListener true
}
- false
}
-
- // we start requesting the bus positions now
- observeBusPositionUpdates()
-
}
- val zoom = 12.0
- val latlngTarget = LatLng(MapLibreFragment.DEFAULT_CENTER_LAT, MapLibreFragment.DEFAULT_CENTER_LON)
- if(!setViewAlready)
- mapReady.cameraPosition = savedCameraPosition ?:CameraPosition.Builder().target(latlngTarget).zoom(zoom).build()
+ var restoredMapState = false
- savedCameraPosition = null
+ restoredMapState = mapStateViewModel.restoreMapState(mapReady)
+ arguments?.let { args ->
+ // if there is a Camera State in the arguments, set it for the new camera (doesn't work yet!)
+ if (!restoredMapState && MapCameraState.checkInBundle(args)) {
+ val initCamState = MapCameraState.fromBundle(args)
+ //map?.let{
+ MapStateViewModel.restoreMapState(mapReady, initCamState)
+ restoredMapState = true
+
+ }
+ }
+ restoredCameraInMap = restoredMapState
+ Log.d(DEBUG_TAG, "Restored map state: $restoredMapState")
- if(shouldMapLocationBeReactivated)
- mapReady.style?.let{ checkInitMapLocation(mapReady,it, context)}
+ if(!restoredMapState) {
+ val zoom = 12.0
+ val latlngTarget = LatLng(MapLibreFragment.DEFAULT_CENTER_LAT, MapLibreFragment.DEFAULT_CENTER_LON)
+ mapReady.cameraPosition = CameraPosition.Builder().target(latlngTarget).zoom(zoom).build()
+ }
}
override fun showOpenStopWithSymbolLayer(): Boolean {
@@ -1081,7 +1053,7 @@
mapStateViewModel.lastOpenStopID.postValue(shownStopInBottomSheet?.ID)
}
- override fun onStop() {
+ /*override fun onStop() {
super.onStop()
if(locationInitialized)
shouldMapLocationBeReactivated = locationComponent.isLocationComponentEnabled
@@ -1089,10 +1061,13 @@
shouldMapLocationBeReactivated = false
}
+ */
+
override fun onDestroyView() {
- map?.run {
+ map?.let {
Log.d(DEBUG_TAG, "Saving camera position")
- savedCameraPosition = cameraPosition
+ //savedCameraPosition = cameraPosition
+ mapStateViewModel.saveMapState(it)
}
super.onDestroyView()
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
--- a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
@@ -45,7 +45,6 @@
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
@@ -62,12 +61,12 @@
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.adapters.StopNearbyAdapter;
import it.reyboz.bustorino.backend.*;
-import it.reyboz.bustorino.util.Permissions;
+import it.reyboz.bustorino.util.PermissionsHelper;
import it.reyboz.bustorino.viewmodels.IntroViewModel;
import it.reyboz.bustorino.viewmodels.SearchStopsDBViewModel;
import org.jetbrains.annotations.NotNull;
-import static it.reyboz.bustorino.util.Permissions.LOCATION_PERMISSIONS;
+import static it.reyboz.bustorino.util.PermissionsHelper.LOCATION_PERMISSIONS;
/**
@@ -679,7 +678,7 @@
final Context con = requireContext();
Log.w(DEBUG_TAG, "OnResume called, setupOnStart: "+ setupOnStart);
//recheck the introduction activity has been run
- if(Permissions.bothLocationPermissionsGranted(con)){
+ if(PermissionsHelper.bothLocationPermissionsGranted(con)){
Log.d(DEBUG_TAG, "Location permission OK");
} //don't request permission
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt
@@ -38,10 +38,8 @@
import it.reyboz.bustorino.backend.Stop
import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate
import it.reyboz.bustorino.backend.mato.MQTTMatoClient
-import it.reyboz.bustorino.data.PreferencesHolder
import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops
import it.reyboz.bustorino.map.MapLibreLocationEngine
-import it.reyboz.bustorino.map.MapLibreStyles
import it.reyboz.bustorino.viewmodels.StopsMapViewModel
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
@@ -152,40 +150,29 @@
}
}
centerUserButton.setOnClickListener {
- if(context!=null && locationComponent.isLocationComponentEnabled) {
- val location = locationComponent.lastKnownLocation
-
- location?.let {
- mapView?.getMapAsync { map ->
- map.animateCamera(CameraUpdateFactory.newCameraPosition(
- CameraPosition.Builder().target(LatLng(location.latitude, location.longitude)).build()), 500)
+ locationComponent?.let { if (context != null && it.isLocationComponentEnabled) {
+ val location = it.lastKnownLocation
+
+ location?.let {
+ mapView?.getMapAsync { map -> map.animateCamera(
+ CameraUpdateFactory.newCameraPosition(
+ CameraPosition.Builder().target(LatLng(location.latitude, location.longitude))
+ .build()
+ ), 500
+ )
+ }
}
}
}
}
followUserButton.setOnClickListener {
// onClick user following button
- if(context!=null && locationInitialized && locationComponent.isLocationComponentEnabled){
+ if(context!=null && locationInitialized && (locationComponent?.isLocationComponentEnabled ?: false)){
// CameraMode.TRACKING makes the camera move and jump to the location
setFollowUserLocation(!followingUserLocation)
}
}
- //locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
- /*
- if (Permissions.bothLocationPermissionsGranted(requireContext()) && deviceHasGpsProvider()) {
-
- requestInitialUserLocation()
- } else{
- if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
- //TODO: show dialog for permission rationale
- Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT)
- .show()
- }
- // PERMISSIONS REQUESTED AFTER MAP SETUP
- }
-
- */
// Setup close button
rootView.findViewById<View>(R.id.btnClose).setOnClickListener {
hideStopOrBusBottomSheet()
@@ -239,35 +226,18 @@
}
- /**
- * This method sets up the map and the layers
- */
- override fun onMapReady(mapReady: MapLibreMap) {
- this.map = mapReady
- val context = requireContext()
- val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context))
-
- val builder = Style.Builder().fromJson(mjson!!)
-
- mapReady.setStyle(builder) { style ->
- mapStyle = style
- //setupLayers(style)
- addImagesStyle(style)
-
- //init stop layer with this
- val stopsInCache = stopsViewModel.stopsToShow.value
- if(stopsInCache.isNullOrEmpty()) initStopsLayer(style, null)
- else displayStops(stopsInCache)
+ override fun onStyleLoaded(mapReady: MapLibreMap,style: Style) {
+ //init stop layer with this
+ val stopsInCache = stopsViewModel.stopsToShow.value
+ if(stopsInCache.isNullOrEmpty()) initStopsLayer(style, null)
+ else displayStops(stopsInCache)
- if(showBusLayer) setupBusLayer(style, withLabels = true, busIconsScale = 1.2f)
-
- // Start observing data now that everything is set up
- observeStops()
-
- checkInitMapLocation(mapReady,style, context)
- }
+ if(showBusLayer) setupBusLayer(style, withLabels = true, busIconsScale = 1.2f)
+ checkInitMapLocation(mapReady,style, requireContext())
+ }
+ override fun setupMapListenersOnInit(mapReady: MapLibreMap) {
mapReady.addOnCameraIdleListener {
map?.let {
val newBbox = it.projection.visibleRegion.latLngBounds
@@ -285,12 +255,14 @@
}
mapReady.addOnMapClickListener { point ->
- onMapClickReact(point)
+ onMapClickReact(point)
}
- // we start requesting the bus positions now
- observeBusPositionUpdates()
+ }
- //Restoring data
+ override fun onMapLibreInitialized(mapReady: MapLibreMap) {
+ // Start observing data now that everything is set up
+ observeStops()
+ observeBusPositionUpdates()
if (initialStopToShow!=null && initialStopToShow?.hasCoords() == true){
val s = initialStopToShow!!
@@ -305,15 +277,15 @@
//restore the map state here
map?.let{
boundsRestored = mapStateViewModel.restoreMapState(it)
- mapStateViewModel.lastOpenStopID.value?.let{ sID->
- val s= stopsViewModel.getStopByID(sID)
- if (s==null) {
- if(sID.isNotEmpty())
- Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
- }
- else{
- openStopInBottomSheet(s) }
- }
+ mapStateViewModel.lastOpenStopID.value?.let{ sID->
+ val s= stopsViewModel.getStopByID(sID)
+ if (s==null) {
+ if(sID.isNotEmpty())
+ Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
+ }
+ else{
+ openStopInBottomSheet(s) }
+ }
}
if(!boundsRestored){
@@ -322,20 +294,14 @@
val defaultLoc = LatLng(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON)
val proposedLoc = lastLoc?.let{ LatLng(lastLoc.latitude, lastLoc.longitude)}
val targetLoc = if(proposedLoc == null || proposedLoc.distanceTo(defaultLoc) > MAX_DIST_KM*1000)
- defaultLoc
- else proposedLoc
+ defaultLoc
+ else proposedLoc
mapReady.cameraPosition = CameraPosition.Builder().target(targetLoc).zoom(DEFAULT_ZOOM).build()
}
restoredMapCamera.set(boundsRestored)
-
-
}
- mapInitialized = true
-
- //pendingLocationActivation = true
- //positionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS)
}
@@ -592,36 +558,39 @@
@SuppressLint("MissingPermission")
override fun onMapLocationComponentInitialized() {
//locationComponent.cameraMode = CameraMode.TRACKING
-
- locationComponent.renderMode = RenderMode.COMPASS
- locationComponent.locationEngine?.apply{
- // this is only called once
- getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
- override fun onSuccess(res: LocationEngineResult?) {
- Log.d(DEBUG_TAG, "Got the last location, ${res?.lastLocation}")
- res?.lastLocation?.let { loc ->
- if(mapInitialized){
- val newLocation = LatLng(loc.latitude, loc.longitude)
- //center the position only if it is close enough and we are not showing a stop
- if(!showingBusStopOrVehicle() && newLocation.distanceTo(DEFAULT_LATLNG) < MAX_DIST_KM * 1000)
- map?.cameraPosition = CameraPosition.Builder().target(LatLng(loc.latitude, loc.longitude)).build()
+ locationComponent?.let { locComp ->
+
+ locComp.renderMode = RenderMode.COMPASS
+ locComp.locationEngine?.apply {
+ // this is only called once
+ getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
+ override fun onSuccess(res: LocationEngineResult?) {
+ Log.d(DEBUG_TAG, "Got the last location, ${res?.lastLocation}")
+ res?.lastLocation?.let { loc ->
+ if (mapInitialized) {
+ val newLocation = LatLng(loc.latitude, loc.longitude)
+ //center the position only if it is close enough and we are not showing a stop
+ if (!showingBusStopOrVehicle() && newLocation.distanceTo(DEFAULT_LATLNG) < MAX_DIST_KM * 1000)
+ map?.cameraPosition =
+ CameraPosition.Builder().target(LatLng(loc.latitude, loc.longitude)).build()
+ } else
+ mapStateViewModel.userLocationToShow = loc
}
- else
- mapStateViewModel.userLocationToShow = loc
}
- }
- override fun onFailure(p0: java.lang.Exception) {
- if( p0 is MapLibreLocationEngine.NoLocationException)
+ override fun onFailure(p0: java.lang.Exception) {
+ if (p0 is MapLibreLocationEngine.NoLocationException)
Log.d(DEBUG_TAG, "Cannot find location: ${p0.message}")
- else
- Log.w(DEBUG_TAG, "Failed to get the last location, error: ${p0.message}",)
- }
+ else
+ Log.w(DEBUG_TAG, "Failed to get the last location, error: ${p0.message}",)
+ }
+
+ })
+ }
- })
}
- if(locationEnabledOnDevice){
- if(!showingBusStopOrVehicle() && !hasToShowInitialStop())
+ if (locationEnabledOnDevice) {
+ if (!showingBusStopOrVehicle() && !hasToShowInitialStop())
setFollowUserLocation(true)
}
@@ -698,9 +667,9 @@
*/
private fun setFollowUserLocation(enabled: Boolean){
if(locationInitialized) {
- if (enabled)
- locationComponent.cameraMode = CameraMode.TRACKING
- else locationComponent.cameraMode = CameraMode.NONE
+ locationComponent?.let{
+ it.cameraMode = if(enabled) CameraMode.TRACKING else CameraMode.NONE
+ }
}
//update the icon by updating the livedata
mapStateViewModel.followingUserPosition.value = enabled
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
--- a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
@@ -41,8 +41,8 @@
import it.reyboz.bustorino.middleware.AutoFitGridLayoutManager
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider.LocationUpdateListener
-import it.reyboz.bustorino.util.Permissions
-import it.reyboz.bustorino.util.Permissions.Companion.bothLocationPermissionsGranted
+import it.reyboz.bustorino.util.PermissionsHelper
+import it.reyboz.bustorino.util.PermissionsHelper.Companion.bothLocationPermissionsGranted
import it.reyboz.bustorino.util.StopSorterByDistance
import it.reyboz.bustorino.viewmodels.NearbyStopsViewModel
import java.util.*
@@ -236,7 +236,7 @@
locationProvider!!.addListener(locationUpdateListener)
enableLocationButton.setOnClickListener {
- locationPermissionLauncher.launch(Permissions.LOCATION_PERMISSIONS)
+ locationPermissionLauncher.launch(PermissionsHelper.LOCATION_PERMISSIONS)
}
return root
diff --git a/app/src/main/java/it/reyboz/bustorino/util/Permissions.kt b/app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
rename from app/src/main/java/it/reyboz/bustorino/util/Permissions.kt
rename to app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
--- a/app/src/main/java/it/reyboz/bustorino/util/Permissions.kt
+++ b/app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
@@ -6,25 +6,20 @@
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
-import android.location.Criteria
-import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
-import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
import androidx.core.content.ContextCompat
-import androidx.core.content.ContextCompat.startActivity
import it.reyboz.bustorino.R
import java.util.concurrent.atomic.AtomicInteger
-import kotlin.concurrent.atomics.AtomicInt
-class Permissions private constructor(private val appContext: Context) {
+class PermissionsHelper private constructor(private val appContext: Context) {
/*
@get:RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
@@ -35,8 +30,10 @@
*/
private var askedTimesLocation = AtomicInteger(0)
-
- fun checkRequestLocationPermissions(activity: Activity, launcher: ActivityResultLauncher<Array<String>>): Boolean {
+ /**
+ * Check if we launch the permission request or not
+ */
+ fun checkRequestLocationPermissions(activity: Activity, launcher: ActivityResultLauncher<Array<String>>, maxTimes:Int = 4): Boolean {
//activity.getSharedPreferences(, Context.MODE_PRIVATE)
var launched = false
@@ -49,7 +46,7 @@
*/
val reqTimes = askedTimesLocation.getAndIncrement()
Log.d(DEBUG_TAG, "Requesting location permissions, asked ${reqTimes} times ")
- if(reqTimes > 4){
+ if(reqTimes > maxTimes){
openShowAppSettingsLocationDialog()
} else{
launcher.launch(LOCATION_PERMISSIONS)
@@ -136,11 +133,11 @@
@Volatile
- private var instance: Permissions? = null
+ private var instance: PermissionsHelper? = null
fun getInstance(context: Context) =
instance ?: synchronized(this) {
- instance ?: Permissions(context.applicationContext).also { instance = it }
+ instance ?: PermissionsHelper(context.applicationContext).also { instance = it }
}
}
diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
--- a/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
+++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
@@ -1,12 +1,14 @@
package it.reyboz.bustorino.viewmodels
import android.location.Location
+import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import it.reyboz.bustorino.map.MapCameraState
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMap
+import java.util.concurrent.atomic.AtomicBoolean
class MapStateViewModel : ViewModel() {
@@ -20,12 +22,13 @@
val newBbox = map.projection.visibleRegion.latLngBounds
val cameraState = MapCameraState(
- latitude = newBbox.center.latitude,
- longitude = newBbox.center.longitude,
+ latitude = cp.target?.latitude ?: newBbox.center.latitude,
+ longitude = cp.target?.longitude ?: newBbox.center.longitude,
zoom = cp.zoom,
bearing = cp.bearing,
tilt = cp.tilt
)
+ Log.d(DEBUG_TAG, "Saved camera state: $cameraState")
savedCameraState = cameraState
}
@@ -34,11 +37,18 @@
}
var userLocationToShow: Location? = null
+ var mapInitOnce = AtomicBoolean(false)
val locationUserActive = MutableLiveData(false)
+ //val locationUserAvailable = MutableLiveData(false)
val followingUserPosition = MutableLiveData(false)
val locationDeviceEnabled = MutableLiveData(false)
+ fun setLocationNotAvailable(){
+ //locationUserAvailable.value = false
+ locationUserActive.value = false
+ }
+
companion object{
fun restoreMapState(map: MapLibreMap, savedCameraState: MapCameraState?): Boolean {
val state = savedCameraState ?: return false
@@ -48,7 +58,10 @@
.bearing(state.bearing)
.tilt(state.tilt)
.build()
+ Log.d(DEBUG_TAG, "Restored camera state: $state")
return true
}
+
+ const val DEBUG_TAG ="BusTO-MapState"
}
}
\ No newline at end of file
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Tue, Nov 17, 23:22 (23 h, 51 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263365
Default Alt Text
D264.1794957736.diff (47 KB)
Attached To
Mode
D264: Make location component nullable, simplify LinesDetailFragment
Attached
Detach File
Event Timeline