Xamarin表单服务无法在后台存活

时间:2019-05-06 19:16:22

标签: service xamarin.forms xamarin.android background-process

我正在使用Xamarin.Forms,并且为android部分实现了一项服务,以使后台跟踪保持活动状态。但是,当我将应用程序置于后台并打开屏幕时,该应用程序甚至无法持续运行5分钟,并且该服务消失了,因为我看到该服务开始的通知已消失并且位置不再打勾。

我正在使用Huawei P Smart,我知道华为喜欢杀死后台应用程序,但是它可以在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();

我正在使用James Montemagno的GeolocatorPlugin,但是我想这对为什么服务没有保持活动状态没有意义,因为无论实现如何,服务都应该保持运行状态。

我也许还需要提到我没有xamarin的经验,因为这是我的第一个项目,所以这可能是一个简单的错误。

0 个答案:

没有答案