Xamarin формирует службу, не оставаясь в живых на заднем плане - PullRequest
0 голосов
/ 06 мая 2019

Я использую Xamarin.Forms и реализовал сервис для части Android, чтобы поддерживать фоновое отслеживание.Но когда я помещаю приложение в фоновый режим и переворачиваю экран, приложение не работает даже 5 минут, и служба умирает, поскольку я вижу, что уведомление, с которого запускается служба, пропало, и местоположения больше не отмечаются.

Я использую Huawei P Smart и знаю, что Huawei любит убивать приложения в фоновом режиме, но он работает в Cordova, где я использовал плагин, аналогичный тому, который я использую сейчас, на том же телефоне.

Мой сервисный код:

[assembly: Xamarin.Forms.Dependency(typeof(GeolocationService))]
namespace MyApp.Droid.Services
{
[Service]
public class GeolocationService : Service, IGeolocationBackgroundService
{
    private static readonly string CHANNEL_ID = "geolocationServiceChannel";
    public GeolocatorPageViewModel ViewModel { get; private set; }

    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    public GeolocationService()
    {
        CreateNotificationChannel();
    }

    private void CreateNotificationChannel()
    {
        NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID,
            "GeolocationService", Android.App.NotificationImportance.Default);
        NotificationManager manager = Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

        manager.CreateNotificationChannel(serviceChannel);

    }

    //[return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        var newIntent = new Intent(this, typeof(MainActivity));
        newIntent.AddFlags(ActivityFlags.ClearTop);
        newIntent.AddFlags(ActivityFlags.SingleTop);

        var pendingIntent = PendingIntent.GetActivity(this, 0, newIntent, 0);

        var builder = new Notification.Builder(this, CHANNEL_ID);
        var notification = builder.SetContentIntent(pendingIntent)
            .SetSmallIcon(Resource.Drawable.ic_media_play_light)
            .SetAutoCancel(false)
            .SetTicker("Locator is recording")
            .SetContentTitle("GeolocationService")
            .SetContentText("Geolocator is recording for position changes.")
            .Build();

        StartForeground(112, notification);
        //ViewModel = new GeolocatorPageViewModel();
        return StartCommandResult.Sticky;
    }


    public void StartService()
        => Forms.Context.StartService(new Intent(Forms.Context, typeof(GeolocationService)));


    public void StartTracking()
    {
        ViewModel = new GeolocatorPageViewModel();
        ViewModel.StartTrackingCommand.Execute(null);
    }
  }
}

Он использует ViewModel, который реализован следующим образом:

public class GeolocatorPageViewModel
{
    LocationService lservice;
    public GeolocatorPageViewModel()
    {
        lservice = new LocationService();
    }

    public ICommand StartTrackingCommand => new Command(async () =>
    {
        if (CrossGeolocator.Current.IsListening)
        {
            await CrossGeolocator.Current.StopListeningAsync();
        }

        CrossGeolocator.Current.DesiredAccuracy = 100;
        CrossGeolocator.Current.PositionChanged += Geolocator_PositionChanged;

        await CrossGeolocator.Current.StartListeningAsync(
            TimeSpan.FromSeconds(3), 5);
    });

    private void Geolocator_PositionChanged(object sender, PositionEventArgs e)
    {
        var position = e.Position;
        lservice.SendLocationToServerAsync(position.Latitude, position.Longitude, position.Timestamp.DateTime, position.Heading, position.Speed, position.Accuracy, position.Altitude, position.AltitudeAccuracy);
    }
}

Я вызываю службу через интерфейс:

public interface IGeolocationBackgroundService {
    void StartService();
    void StartTracking();
}

Я называю службу следующим образом:

var svc = DependencyService.Get<IGeolocationBackgroundService>();
svc.StartService();
svc.StartTracking();

Я использую GeolocatorPlugin Джеймса Монтемагно, но, думаю, это не имеет никакого значения, почему служба не работает, как бы ни была реализация, службы должны продолжать работать.

Также мне, возможно, нужно упомянуть, что у меня нет опыта работы с xamarin, так как это мой первый проект, так что это может быть простой ошибкой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...