Как использовать интерфейс - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь создать свое первое приложение xamarin, которое я создаю с использованием форм.Одной из функций приложения является отправка местоположений пользователей, и они должны делать это, даже если приложение находится в фоновом режиме.Поэтому я наткнулся на GeolocatorPlugin Джеймса Монтемагно, который обещал сделать именно это.

Поскольку в документации было не очень ясно, как реализовать его плагин в фоновом режиме, я просмотрел закрытые вопросы проектов и нашел парня, который далпример простого случая использования плагина с сервисом.(https://github.com/jamesmontemagno/GeolocatorPlugin/issues/272)

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

В моем общем проекте я поместил интерфейс и модель представления, а в проекте xamarin.android я поставил сервис.

Интерфейс - IGeolocationBackgroundService:

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

Модель представления - GeolocatorPageViewModel:

public class GeolocatorPageViewModel
{
    public Position _currentUserPosition { get; set; }
    public string CoordinatesString { get; set; }
    public List<string> userPositions { get; set; }

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

        CrossGeolocator.Current.DesiredAccuracy = 25;
        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;
        _currentUserPosition = position;
        var positionString = $"Latitude: {position.Latitude}, Longitude: {position.Longitude}";
        CoordinatesString = positionString;
        Device.BeginInvokeOnMainThread(() => CoordinatesString = positionString);
        userPositions.Add(positionString);
        Debug.WriteLine($"Position changed event. User position: {CoordinatesString}");
    }
}

Служба - GeolocationService:

[assembly: Xamarin.Forms.Dependency(typeof(GeolocationService))]
namespace MyApp.Droid.Services
{
[Service]
public class GeolocationService : Service, IGeolocationBackgroundService
{
    Context context;

    private static readonly string CHANNEL_ID = "geolocationServiceChannel";
    public GeolocatorPageViewModel ViewModel { get; private set; }

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

    public GeolocationService(Context context)
    {
        this.context = context;
        CreateNotificationChannel();
    }

    private void CreateNotificationChannel()
    {
        NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID,
            "GeolocationService", Android.App.NotificationImportance.Default);
        NotificationManager manager = 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()
        => context.StartService(new Intent(context, typeof(GeolocationService)));


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

Итак, я должен запустить службу, и я не привык к интерфейсам,так как мне назвать интерфейс?

1 Ответ

0 голосов
/ 06 мая 2019

используйте DependencyService, чтобы получить ссылку на ваш сервис и затем запустить его

var svc = DependencyService.Get<IGeolocationBackgroundService>();
svc.StartService();
svc.StartTracking();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...