Background location service stops working after a few minutes [closed] - xamarin.forms

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
Estoy realizando una app en xamarin forms y xamarin.android para el tracking de una servicio, ya tengo creado mi servicio y la peticion de la ubicacion, el problema radica en que el dispositivo deja de obtener la ubicacion luego de un tiempo cuando se encuentra suspendido o en segundo plano, esto me pasa solo en mi dispositivo fisico ya que con el emulador no se me presenta este error
Service
[Service]
public class AndroidLocationService : Service
{
CancellationTokenSource _cts;
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10001;
public static string NAME = "com.swfactorygroup.bongoadm.WakefulIntentService";
private static volatile PowerManager.WakeLock lockStatic = null;
[MethodImpl(MethodImplOptions.Synchronized)]
private static PowerManager.WakeLock GetLock(Context context)
{
if (lockStatic == null)
{
PowerManager manager = (PowerManager)context.GetSystemService(Context.PowerService);
lockStatic = manager.NewWakeLock(WakeLockFlags.Partial, NAME);
lockStatic.SetReferenceCounted(false);
}
return (lockStatic);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
_cts = new CancellationTokenSource();
Notification notification = new NotificationHelper().GetServiceStartedNotification();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
wakeLock.Acquire();
Task.Run(() => {
try
{
var locShared = new GetLocationService();
locShared.Run(_cts.Token).Wait();
}
catch (Android.OS.OperationCanceledException)
{
}
finally
{
if (_cts.IsCancellationRequested)
{
var message = new StopServiceMessage();
Device.BeginInvokeOnMainThread(
() => MessagingCenter.Send(message, "ServiceStopped")
);
}
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (wakeLock.IsHeld)
{
try
{
wakeLock.Release();
}
catch (Exception ex)
{
Log.Error(Class.SimpleName, "Exception when releasing wakelock", ex);
//Log exception when releasing wakelock
}
}
}
}, _cts.Token);
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
if (_cts != null)
{
_cts.Token.ThrowIfCancellationRequested();
_cts.Cancel();
}
base.OnDestroy();
}
}
public class GetLocationService
{
readonly bool stopping = false;
SQLiteHelper _bd = App.BDSQLite;
public GetLocationService()
{
}
public async Task Run(CancellationToken token)
{
await Task.Run(async () => {
while (!stopping)
{
token.ThrowIfCancellationRequested();
try
{
await Task.Delay(10000);
var request = new GeolocationRequest(GeolocationAccuracy.Best);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
var message = new LocationMessage
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send(message, "Location");
});
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
var errormessage = new LocationErrorMessage();
MessagingCenter.Send(errormessage, "LocationError");
});
}
}
return;
}, token);
}
}
I tried using a PowerManager.WakeLock, but it is not poorly implemented, it seems that the device will kill the process after a few minutes

Related

Xamarin.Azure.Notification.Hub (3.1.1) crashing in iOS 16.1

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
try
{
string ConnectionString = AppConfiguration.NotificationHubConnectionString;
string hubPath = AppConfiguration.NotificationHubPath;
if (!string.IsNullOrEmpty(ApplicationContext.Instance.APIVersion))
{
ConnectionString = AppConfiguration.NotificationHubConnectionStringv2;
hubPath = AppConfiguration.NotificationHubPath2;
}
NSSet tags = null;
SBNotificationHub hub;
byte[] bytes = deviceToken.ToArray();
string[] hexArray = bytes.Select(b => b.ToString("x2")).ToArray();
var tokenString = string.Join(string.Empty, hexArray);
hub = new SBNotificationHub(ConnectionString, hubPath);
tags = new NSSet(new string[] {
Mvx.IoCProvider.Resolve<IDeviceIdentifier>()?.GetRestaurantId()?.ToLower() });
hub.UnregisterAll(deviceToken, error =>
{
if (error != null)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogEvent(Enums.CustomEvents.Notifications.ToString(), error.Description);
return;
}
hub.RegisterNative(deviceToken, tags, errorCallback =>
{
if (errorCallback != null)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogEvent(Enums.CustomEvents.Notifications.ToString(), errorCallback.Description);
}
});
});
Preferences.Set("DeviceTokens", tokenString);
PushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
}
catch (Exception ex)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogException(nameof(RegisteredForRemoteNotifications), ex);
}
}
Xamarin.Azure.Notification.Hub (3.1.1) - iOS 16.1
App is crashing at RegisterNative method... This logic was working all this while..till ios was upgraded to 16 on ipad
What changed in iOS 16

How do i add record from data table

I would add record to my table with a form to fill out, but there is a error from ListerPF()
"Object reference not set to an instance of an object"
Here is the whole process:
await App.methode.AddNewPF(Label_NumeroNF.Text, DatePicker_Date.Date, Editor_LibelleNF.Text, Picker_TypeFrais.SelectedItem.ToString(), double.Parse(Entry_Quantite.Text), double.Parse(Entry_Tarif.Text), double.Parse(Entry_Montant.Text), double.Parse(Entry_MontantTotal.Text), CheckBox_CCEntreprise.IsChecked, int.Parse(Entry_Imputation.Text));
Navigation.PushAsync(new PostesNF());
And the code behind "AddNewPF" is:
public async Task AddNewPF(string numero , DateTime date, string libelle, string typeFrais, double quantite, double tarif, double montant, double montantTotal, bool carteCredit, int imputationCC)
{
int result = 0;
try
{
result = await connection.InsertAsync(new DB_PosteNF { Numero = numero, Date = date, Libelle = libelle, TypeFrais = typeFrais, Quantite = quantite, Tarif = tarif, Montant = montant, MontantTotal = montantTotal, CarteCredit = carteCredit, ImputationCC = imputationCC});
StatutMessage = $"{result} poste de frais ajouté : {numero} | {typeFrais} ";
}
catch (Exception ex)
{
StatutMessage = $"Impossible d'ajouter le poste de frais avec le numéro: {numero}. \nErreur : {ex.Message}";
}
}
When the "PosteNF" page appears, I have this code
protected override async void OnAppearing()
{
base.OnAppearing();
CollectionViewPF.ItemsSource = await App.methode.ListerPF();
}
the problematic code "ListerPF" is:
public async Task<List<DB_PosteNF>> ListerPF(DB_ListeNF datareceived)
{
try
{
string numero = datareceived.Numero;
//return await connection.Table<DB_PosteNF>().ToListAsync();
return await connection.Table<DB_PosteNF>().Where(x => x.Numero == numero).ToListAsync();
}
catch (Exception ex)
{
StatutMessage = $"Impossible d'afficher la liste des postes de frais. \nErreur : {ex.Message}";
}
return new List<DB_PosteNF>();
}
But when I go back to the "PostesNF" page, the registered data is not displayed. Thanks for your help !
Per your code snippets, the model is DB_PosteNF with 10 properties.The key is that when you retrieve the records from the data table, I think you need a ObservableCollection<DB_PosteNF> to receive these entities that read from the database.Below is the code snippets for your reference:
First, define a UserCollection using ObservableCollection
public ObservableCollection<User> UserCollection { get; set; }
Then, in OnAppearing method:
protected override async void OnAppearing()
{
base.OnAppearing();
UserDB db = await UserDB.Instance;
List<User> a = await db.GetUserAsync();
UserCollection = new ObservableCollection<User>(a);
userinfodata.ItemsSource = UserCollection;
}
PS: In my case, the mode is User.

How to save current location?

I have a question. I am working on mobile app where my user can store experience from trip by loggin current location.
I am connected to SQLite fo now and I am just exploring the Geolocator nuget from James Monemagno. SO far I can get the pin on map with current location, but I am unsure how to store the location in databse. I guess it wont be"position" and it must be Latitude and Longitude but then how will i get again the picture with the pin displayed under my post? Do you guys have some experience?
Public clas NoteViewMode : BaseViewModel
{
/////
private string _location;
public string Location
{
get { return _location; }
set
{
_location = value;
OnPropertyChanged();
}
}
public double _latitude;
public double Latitude
{
get { return _latitude; }
set
{
_latitude = value;
OnPropertyChanged();
}
}
private double _longitude;
public double Longitude
{
get { return _longitude; }
set
{
_longitude = value;
OnPropertyChanged();
}
}
}
public Map()
{
InitializeComponent();
GetPremissions();
BindingContext = ViewModel = new AdLogEntryViewModel();
}
private async void GetPremissions()
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
{
await DisplayAlert("We need location", "", "Ok");
}
var result = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (result.ContainsKey(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
status = result[Plugin.Permissions.Abstractions.Permission.LocationWhenInUse];
}
if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
locationsMap.IsShowingUser = true;
hasLocationPermission = true;
GetLocation();
}
else
{
await DisplayAlert("Location denied", "", "");
}
}
catch (Exception ex)
{
await DisplayAlert("erroe", ex.Message, "ok");
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
locator.PositionChanged += Locator_PositionChanged;
await locator.StartListeningAsync(TimeSpan.Zero, 100);
}
GetLocation();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= Locator_PositionChanged;
}
void Locator_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
MoveMap(e.Position);
}
private async void GetLocation()
{
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
MoveMap(position);
}
}
private async void MoveMap(Position position)
{
var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var span = new Xamarin.Forms.Maps.MapSpan(center, 1, 1);
locationsMap.MoveToRegion(span);
}
you can programmatically add a Pin to a Map
Pin pin = new Pin
{
Label = "Santa Cruz",
Address = "The city with a boardwalk",
Type = PinType.Place,
Position = new Position(36.9628066, -122.0194722)
};
map.Pins.Add(pin);

Request camera permissions xamarin forms

I have an app that needs permissions for the camera, this is well implemented, but asks for permission on the home screen (splash). What I would like is to appear after logging in or on a specific page (Is this possible?). And as I could implement the same for IOS, I thank you very much for your help and have a great day.
Thanks for you help.
Here my code
MainActivity.cs
const int requestCameraId = 0;
const int requestStorageId = 1;
const int requestId = 2;
readonly string[] permissions =
{
Android.Manifest.Permission.Camera,
Android.Manifest.Permission.ReadExternalStorage,
Android.Manifest.Permission.WriteExternalStorage,
Android.Manifest.Permission.Internet,
Android.Manifest.Permission.ForegroundService,
Android.Manifest.Permission.RequestCompanionUseDataInBackground,
Android.Manifest.Permission.RequestCompanionRunInBackground,
Android.Manifest.Permission.StatusBar,
Android.Manifest.Permission.Vibrate,
Android.Manifest.Permission.Flashlight
};
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
switch (requestCode)
{
case requestCameraId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permiso concedido para la camara", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permiso denegado para la camara", ToastLength.Short).Show();
}
}
break;
case requestStorageId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permiso concedido para el almacenamiento", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permiso denegado para el almacenamiento", ToastLength.Short).Show();
}
}
break;
}
}
async Task GetCameraPermissionAsync()
{
const string permission = Manifest.Permission.Camera;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permisos para la camara listos", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permisos necesarios");
alert.SetMessage("La aplicación necesita acceder a la camara para tomar una fotografía del trabajo terminado");
alert.SetPositiveButton("Conceder permiso", (senderAlert, args) =>
{
RequestPermissions(permissions, requestCameraId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
}
async Task GetStoragePermissionAsync()
{
const string permission = Manifest.Permission.ReadExternalStorage;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permisos para leer carpetas listos", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permisos necesarios");
alert.SetMessage("La aplicación necesita acceder a sus archivos para subir una imagen con el trabajo terminado");
alert.SetPositiveButton("Conceder permiso", (senderAlert, args) =>
{
RequestPermissions(permissions, requestStorageId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
}
async Task GetPermissionsAsync()
{
await GetCameraPermissionAsync();
await GetStoragePermissionAsync();
RequestPermissions(permissions, requestId);
}
async Task TryToGetPermissions()
{
if ((int)Build.VERSION.SdkInt >= 23)
{
await GetPermissionsAsync();
return;
}
}
protected async override void OnCreate(Bundle savedInstanceState)
{
await TryToGetPermissions();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// RequestPermissions(permissions, requestId);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
Xamarin.Forms.Application.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
CreateNotificationFromIntent(Intent);
//notificationServiceIntent = new Intent(this.BaseContext, typeof(PDANotificationService));
//StartService(notificationServiceIntent);
WireUpLongRunningTask();
var message = new StartLongRunningTaskMessage();
MessagingCenter.Send(message, "StartLongRunningTaskMessage");
}
As #Jason said, your code requests permission on main Activity create, so as soon as you open your app, it will ask for all the permissions you listed. You need to request permission separately.
Say camera permission:
if (CheckSelfPermission(Manifest.Permission.Camera) != (int)Permission.Granted)
{
//request permission
}else
{
//call camera
}
And OnRequestPermissionsResult will be called after user granted/denied the permission request, you can check the result and call camera if the permission was granted.
Please refer to this for detail workflow about permission.

android mapsforge overlay doesn't show in view

I need a little help. I wrote an android app using "org.mapsforge.android.maps".
There I create a custom overlay wich I wanna show in the map. The map is shown but without my Overlay. I see that "mapView.getOverlays().add(myOverlay)" adds myOverlay to mapView but on the screen nothing happens.
Does someone has an idea why not?
Thanks a lot
Tom
#Override
public void onCreate(Bundle savedInstanceState) {
try
{
res= this.getResources();
context=this;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.openstreet);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.main_title_back);
// get the pointers to different system services
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.myLocationListener = new MyLocationListener(this);
if(getIntent().hasExtra("comingfrom") == true)
comingfrom = getIntent().getExtras().getString("comingfrom");
if(getIntent().hasExtra("latitude") == true)
mlatitude = getIntent().getExtras().getDouble("latitude");
if(getIntent().hasExtra("longitude") == true)
mlongitude = getIntent().getExtras().getDouble("longitude");
initMapView();
Log.i(Properties.getProgramname(), "OpenStreetActivity->onCreate: Übergebene Koordinate Lat=" + mlatitude + " Lon=" + mlongitude);
if (comingfrom.equals("ButtonArea"))
{
LoadData();
}
else
{
}
if (this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
initMyLocation(true);
} else {
Toast.makeText(this,"GPS Provider not enabled",Toast.LENGTH_LONG).show();
}
// create a GeoPoint with the latitude and longitude coordinates
GeoPoint geoPoint = new GeoPoint(mlatitude, mlongitude);
mapController.setCenter(geoPoint);
mapController.setZoom(16);
}
catch (Exception ex)
{
Log.e(Properties.getProgramname(), "Fehler in OpenStreetActivity->onCreate: " + ex.getLocalizedMessage());
Toast.makeText(this,"UI problem " + ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* Initialize the OSM
*
*/
private void initMapView()
{
settingsLayer = new TJHookerSettingsLayer(this);
Cursor cur = settingsLayer.ladeSettings();
String filename =cur.getString(cur.getColumnIndex(TJHookerSettingsTables.MAPFILE));
cur.close();
mapView = (MapView) this.findViewById(R.id.openmapview);
this.mapView.setClickable(true);
this.mapView.setBuiltInZoomControls(true);
this.mapView.setFocusable(true);
if (!this.mapView.getMapGenerator().requiresInternetConnection() ) {
File file = new File(filename);
if (file.exists())
mapView.setMapFile(new File(filename));
else
Toast.makeText(this,"Problem: Mapfile not found. Please correct the path of your mapfile",Toast.LENGTH_LONG).show();
}
mapController = this.mapView.getController();
}
/**
* Show the current location of my position
*
*/
private void initMyLocation(boolean centerAtFirstFix)
{
try
{
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = this.locationManager.getBestProvider(criteria, true);
this.itemizedMyLocationOverlay = new ArrayItemizedOverlay(null);
this.overlayMyLocationItem = new OverlayItem();
this.overlayMyLocationItem.setMarker(ItemizedOverlay.boundCenter(getResources().getDrawable(R.drawable.my_location)));
this.itemizedMyLocationOverlay.addItem(this.overlayMyLocationItem);
this.mapView.getOverlays().add(this.itemizedMyLocationOverlay);
this.myLocationListener.setCenterAtFirstFix(centerAtFirstFix);
this.locationManager.requestLocationUpdates(bestProvider, 1000, 0, this.myLocationListener);
}
catch(Exception ex)
{
Log.e(Properties.getProgramname(), "Fehler in OpenStreetActivity->initMyLocation: " + ex.getLocalizedMessage());
Toast.makeText(OpenStreetActivity.this, "!initMyLocation: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
// neuen Thread starten
private void LoadData()
{
if(mlongitude > 0 && mlatitude > 0)
{
SystemInformation sys = new SystemInformation();
if(sys.isNetworkAvailable(this))
{
// Neuen Thread startenn der die Kontakte laden soll. Activity wir schon angezeigt
prog = ProgressDialog.show(this, res.getString(R.string.gc40_progtitle), "", true, false);
prog.setMessage(Html.fromHtml("<font color='white'>" + res.getString(R.string.gc40_progtext) + "</font>"));
pdIsShow=true;
Thread thread = new Thread(this);
thread.start();
}
}
}
#Override
public void run() {
GCApiRequests _apiRequests= new GCApiRequests();
try {
lc = _apiRequests.GetCacheByArea(Properties.getGCAccessToken(), mlongitude, mlatitude,"5000", GeocachingConstants.maxCachesPerPage);
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(Properties.getProgramname(), "KartenAnzeigenActivity->Fehler in run: " + e.getLocalizedMessage());
handler.sendEmptyMessage(1);
}
}
// Wenn Thread alle Kontakte geladen hat, dann in ListView anzeigen
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (pdIsShow)
prog.dismiss();
setOverlayCaches();
}
};
private void setOverlayCaches()
{
try {
CacheType typ = new CacheType();
lc.trimToSize();
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahlgefundener Caches=" +lc.size());
/** So, jetzt gehen wir erstmal durch alle Logs von geocaching.com durch */
// create an ItemizedOverlay with the default marker
CacheOpenStreetMapItemizedOverlay myOverlay= new CacheOpenStreetMapItemizedOverlay(getResources().getDrawable(typ.getCacheType(2)), context);
for(Geocache cache: lc)
{
// create a GeoPoint with the latitude and longitude coordinates
int lat = (int) (Double.parseDouble(cache.GetLatitude()) * 1e6);
int lon = (int) (Double.parseDouble(cache.GetLongitude()) * 1e6);
GeoPoint geoPoint = new GeoPoint(lat,lon);
// create an OverlayItem with title and description
OverlayItem item = new OverlayItem(geoPoint, cache.GetCacheName(), cache.GetGCCode(),
getResources().getDrawable(typ.getCacheType(Integer.parseInt(cache.GetCacheType()))));
myOverlay.addOverlay(item);
}
myOverlay.requestRedraw();
// add the ArrayItemizedOverlay to the MapView
//if (traditionellOverlay != null)
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl Overlay items=" + myOverlay.size());
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl MapView Overlays=" + mapView.getOverlays().size());
mapView.getOverlays().add(myOverlay);
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl MapView Overlays=" + mapView.getOverlays().size());
} catch (Exception e) {
Log.e(Properties.getProgramname(), "KartenAnzeigenActivity->Fehler in setOverlayCaches: " + e.getLocalizedMessage());
}
}
/** Back-Button in Titlebar wurde gedrückt */
public void PressTitleBackButton_Click(View view)
{
/** Durch ein finish() wird der Back-Button Effekt ausgelöst. */
finish();
}
Solved!
You have to rewrite the code to:
int cachetyp = typ.getCacheType(Integer.parseInt(cache.GetCacheType()));
Drawable itemMarker = getResources().getDrawable(cachetyp);
// Without that the icons aren't displayed. So you NEED it
itemMarker.setBounds(0, 0, itemMarker.getIntrinsicWidth(), itemMarker.getIntrinsicHeight());
The item need the bounds.....

Categories

Resources