这可以通过C#的概念来实现
>依赖服务
>活动
需要有4个类来实现这样的实现:
> PCL中的接口(例如,CurrentLocationService.cs),其中定义了事件处理程序.
namespace NAMESPACE
{
public interface CurrentLocationService
{
void start();
event EventHandler positionChanged;
}
}
>使用依赖关系服务在xxx.Droid项目(例如CurrentLocationService_Android.cs)中实现PCL的接口
class CurrentLocationService_Android : CurrentLocationService
{
public static CurrentLocationService_Android mySelf;
public event EventHandler 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));
}
}
> PCL中的ContentPage – 它将具有接口实现的对象.
对象可以通过获得
public CurrentLocationService LocationService
{
get
{
if(currentLocationService == null)
{
currentLocationService = DependencyService.Get();
currentLocationService.positionChanged += OnPositionChange;
}
return currentLocationService;
}
}
private void OnPositionChange(object sender, PositionEventArgs e)
{
Debug.WriteLine("Got the update in ContentPage from service ");
}
> xxx.Droid项目中的后台服务.此服务将引用依赖服务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();
}
}
注意:需要根据用法创建PositionEventArgs类,以在服务和ContentPage之间传递数据.
这对我来说就像魅力一样.
希望这对你有所帮助.