本文最后更新于 222 天前,其中的信息可能已经有所发展或是发生改变。
BindingHelper.cs
using Android.Content;
using Android.OS;
using Android.Util;
public class BinderX<TService, TActivity> : Binder
where TService : Service where TActivity : Activity
{
public BinderX(TService service)
{
Service = service;
}
public TService Service { get; }
public ServiceConnectionX<TActivity, TService>? ServiceConnection { get; set; }
public TActivity? Activity => ServiceConnection?.Activity;
}
public class ServiceConnectionX<TActivity, TService> : Java.Lang.Object, IServiceConnection
where TActivity : Activity where TService : Service
{
public ServiceConnectionX(TActivity activity)
{
Activity = activity;
}
public TActivity Activity { get; }
public BinderX<TService, TActivity>? Binder { get; set; }
public TService? Service => Binder?.Service;
public event EventHandler? Connected;
public event EventHandler? Disconnected;
public void OnServiceConnected(ComponentName? name, IBinder? service)
{
Binder = service as BinderX<TService, TActivity>;
Binder.ServiceConnection = this;
Log.Info(GetType().Name, $"OnServiceConnected {name?.ClassName}");
Connected?.Invoke(this, EventArgs.Empty);
}
public void OnServiceDisconnected(ComponentName? name)
{
Binder.ServiceConnection = null;
Binder = null;
Log.Info(GetType().Name, $"OnServiceDisconnected {name?.ClassName}");
Disconnected?.Invoke(this, EventArgs.Empty);
}
}
MainActivity.cs
using Android.Content;
namespace AndroidApp1
{
[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : Activity
{
ServiceConnectionX<MainActivity, MyService> connection;
protected override void OnCreate(Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
connection = new(this);
Intent intent = new(this, typeof(MyService));
BindService(intent, connection, Bind.AutoCreate);
}
protected override void OnDestroy()
{
base.OnDestroy();
UnbindService(connection);
}
}
}
MyService.cs
using Android.Content;
using Android.OS;
namespace AndroidApp1
{
[Service]
public class MyService : Service
{
BinderX<MyService, MainActivity> binder;
public override void OnCreate()
{
base.OnCreate();
binder = new(this);
}
public override IBinder OnBind(Intent? intent)
{
return binder;
}
}
}