This can be achieved using the C # concept.
It is necessary to have 4 classes for such an implementation:
- An interface in the PCL (e.g. CurrentLocationService.cs) with event handlers defined in it.
namespace NAMESPACE { public interface CurrentLocationService { void start(); event EventHandler<PositionEventArgs> positionChanged; } }
- Implementing the PCL interface in an xxx.Droid project (e.g. CurrentLocationService_Android.cs) using the Dependency service
class CurrentLocationService_Android : CurrentLocationService { public static CurrentLocationService_Android mySelf; public event EventHandler<PositionEventArgs> positionChanged; public void start() { mySelf = this; Forms.Context.StartService(new Intent(Forms.Context, typeof(MyService))); } public void receivedNewPosition(CustomPosition pos) { positionChanged(this, new PositionEventArgs(pos)); } }
- ContentPage in PCL - which will have an interface implementation object. Object can be obtained
public CurrentLocationService LocationService { get { if(currentLocationService == null) { currentLocationService = DependencyService.Get<CurrentLocationService>(); currentLocationService.positionChanged += OnPositionChange; } return currentLocationService; } } private void OnPositionChange(object sender, PositionEventArgs e) { Debug.WriteLine("Got the update in ContentPage from service "); }
- Background service in the xxx.Droid project. This service will have a link to the implementation of the dependency service CurrentLocationService.cs
[Service] public class MyService : Service { public string TAG = "MyService"; public override IBinder OnBind(Intent intent) { throw new NotImplementedException(); } public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { Log.Debug(TAG, TAG + " started"); doWork(); return StartCommandResult.Sticky; } public void doWork() { var t = new Thread( () => { Log.Debug(TAG, "Doing work"); Thread.Sleep(10000); Log.Debug(TAG, "Work completed"); if(CurrentLocationService_Android.mySelf != null) { CustomPosition pos = new CustomPosition(); pos.update = "Finally value is updated"; CurrentLocationService_Android.mySelf.receivedNewPosition(pos); } StopSelf(); }); t.Start(); } }
Note. The PositionEventArgs class must be created according to the use for transferring data between the service and ContentPage.
It works for me like a charm.
Hope this would be helpful for you.
source share