Nir*_*hah 7 notifications updates background-service xamarin.forms
我有一个基于XamarinForms的应用程序.
我在Android项目中创建的一个后台服务,该服务希望将数据发送到向用户显示的ContentPage(在PCL中).
我怎样才能将数据传递给ContentPage(从xx.Droid项目到PCL)?
一个解决方案是:
如果有更好的解决方案,请您提供给我?
这可以通过C#的概念来实现
需要有4个类来实现这样的实现:
namespace NAMESPACE
{
public interface CurrentLocationService
{
void start();
event EventHandler<PositionEventArgs> positionChanged;
}
}Run Code Online (Sandbox Code Playgroud)
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));
}
}Run Code Online (Sandbox Code Playgroud)
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 ");
}Run Code Online (Sandbox Code Playgroud)
[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();
}
}Run Code Online (Sandbox Code Playgroud)
注意:需要根据用法创建PositionEventArgs类,以在服务和ContentPage之间传递数据.
这对我来说就像魅力一样.
希望这对你有所帮助.
| 归档时间: |
|
| 查看次数: |
3208 次 |
| 最近记录: |