Я пытаюсь создать приложение xamarin с Android и iOS.
Я создал службу для трансляции местоположения пользователей через определенные промежутки времени, но каждый раз, когда он пытается транслировать (с помощью SendLocationToServer() ), происходит сбой приложение.
[assembly: Xamarin.Forms.Dependency(typeof(LocationServiceImplementation))]
namespace MyAppName.Droid
{
public class LocationServiceImplementation : ILocationService {
public void StartLocationService(string role, string auth) {
Toast.MakeText(Android.App.Application.Context, "Starting", ToastLength.Short).Show();
var intent = new Intent(MainActivity.Instance, typeof(LocationService));
intent.PutExtra("auth", auth);
intent.PutExtra("role", role);
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O) {
MainActivity.Instance.StartForegroundService(intent);
} else {
MainActivity.Instance.StartService(intent);
}
}
public void StopLocationService() {
Toast.MakeText(Android.App.Application.Context, "Stopping", ToastLength.Short).Show();
throw new NotImplementedException();
}
}
Разрешения устанавливаются и запрашиваются в Manifest и MainActivity: сюда входят грубое расположение, точное расположение и постоянное расположение. Чтобы выяснить порядок запроса, потребовалось некоторое время, но теперь он запрашивается правильно.
Эта функция находится в MainActivity проекта Android:
public async Task GetLocationConsent() {
var status = await Permissions.CheckStatusAsync
();
if (status == PermissionStatus.Denied || status == PermissionStatus.Unknown) {
status = await Permissions.RequestAsync();
}
// Only request background location on Android 10 (API level 29) or higher
if (status == PermissionStatus.Granted && Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q) {
var backgroundStatus = await Permissions.CheckStatusAsync();
if (backgroundStatus == PermissionStatus.Denied || backgroundStatus == PermissionStatus.Unknown) {
await Permissions.RequestAsync();
// Check again if permission is not granted, then navigate to settings
backgroundStatus = await Permissions.CheckStatusAsync();
if (backgroundStatus != PermissionStatus.Granted) {
// Inform the user to manually enable background location in settings
Toast.MakeText(Application.Context, "Please enable Location Always in App Permissions.", ToastLength.Long).Show();
var intent = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings);
intent.AddFlags(ActivityFlags.NewTask);
var uri = Android.Net.Uri.FromParts("package", Application.Context.PackageName, null);
intent.SetData(uri);
Application.Context.StartActivity(intent);
// Show a message to guide the user
Toast.MakeText(Application.Context, "Please enable Background Location in App Permissions.", ToastLength.Long).Show();
}
}
}
}
Я пытался расколоть этот орешек столько часов, что ничего не вижу, а срок работы быстро приближается... Любая помощь будет принята с благодарностью. Пожалуйста.
Я пытаюсь запустить фоновую службу на Android, которая периодически передает местоположение пользователя, но при попытке приложение вылетает.
Я пытаюсь создать приложение xamarin с Android и iOS. Я создал службу для трансляции местоположения пользователей через определенные промежутки времени, но каждый раз, когда он пытается транслировать (с помощью SendLocationToServer() ), происходит сбой приложение. [code][Service] public class LocationService : Service { public string role = ""; public string auth = ""; System.Timers.Timer _timer; const string foregroundChannelId = "location_service_channel"; const int serviceId = 209345; const string channelId = "location_service_channel"; const string channelName = "Location Service"; const string endpoint = @"REMOVED FOR STACK OVERFLOW POST";
public override IBinder OnBind(Intent intent) { return null; }
public override void OnCreate() { var notificationManager = (NotificationManager)GetSystemService(NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default) { Description = "Location Service is running" }; notificationManager.CreateNotificationChannel(channel); } }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { StartForeground(serviceId, CreateNotification());
auth = intent.GetStringExtra("authToken"); role = intent.GetStringExtra("role");
private Notification CreateNotification() { var intent = new Intent(MainActivity.Instance, typeof(MainActivity)); intent.AddFlags(ActivityFlags.SingleTop); intent.PutExtra("Title", "Message");
var pendingIntent = PendingIntent.GetActivity(MainActivity.Instance, 0, intent, PendingIntentFlags.UpdateCurrent);
var notificationBuilder = new Notification.Builder(MainActivity.Instance) .SetContentTitle(channelName) .SetContentText("Broadcasting location in the background") .SetSmallIcon(Resource.Drawable.Icon_small) .SetOngoing(true) .SetContentIntent(pendingIntent);
var notificationManager = MainActivity.Instance.GetSystemService(Context.NotificationService) as NotificationManager; if (notificationManager != null) { notificationBuilder.SetChannelId(foregroundChannelId); notificationManager.CreateNotificationChannel(notificationChannel); } }
return notificationBuilder.Build();
//try { // var notification = new Notification.Builder(this, channelId) // .SetContentTitle(channelName) // .SetContentText("Broadcasting location in the background") // .SetSmallIcon(Resource.Drawable.Icon_small) // .SetOngoing(true) // Keep the notification active // .Build();
public void StopLocationService() { Toast.MakeText(Android.App.Application.Context, "Stopping", ToastLength.Short).Show();
throw new NotImplementedException(); } } [/code] Разрешения устанавливаются и запрашиваются в Manifest и MainActivity: сюда входят грубое расположение, точное расположение и постоянное расположение. Чтобы выяснить порядок запроса, потребовалось некоторое время, но теперь он запрашивается правильно. Эта функция находится в MainActivity проекта Android: [code]public async Task GetLocationConsent() { var status = await Permissions.CheckStatusAsync (); if (status == PermissionStatus.Denied || status == PermissionStatus.Unknown) { status = await Permissions.RequestAsync(); }
// Only request background location on Android 10 (API level 29) or higher if (status == PermissionStatus.Granted && Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q) { var backgroundStatus = await Permissions.CheckStatusAsync(); if (backgroundStatus == PermissionStatus.Denied || backgroundStatus == PermissionStatus.Unknown) { await Permissions.RequestAsync();
// Check again if permission is not granted, then navigate to settings backgroundStatus = await Permissions.CheckStatusAsync(); if (backgroundStatus != PermissionStatus.Granted) { // Inform the user to manually enable background location in settings Toast.MakeText(Application.Context, "Please enable Location Always in App Permissions.", ToastLength.Long).Show();
var intent = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings); intent.AddFlags(ActivityFlags.NewTask); var uri = Android.Net.Uri.FromParts("package", Application.Context.PackageName, null); intent.SetData(uri); Application.Context.StartActivity(intent);
// Show a message to guide the user Toast.MakeText(Application.Context, "Please enable Background Location in App Permissions.", ToastLength.Long).Show(); } } } } [/code] Я пытался расколоть этот орешек столько часов, что ничего не вижу, а срок работы быстро приближается... Любая помощь будет принята с благодарностью. Пожалуйста. Я пытаюсь запустить фоновую службу на Android, которая периодически передает местоположение пользователя, но при попытке приложение вылетает.