我正在构建一个Xamarin.Android应用程序。我有一个正在运行的服务,我正在尝试将数据从该服务获取到我拥有的活动。我知道人们对发布过多的代码感到不满,但是我不确定我的问题在哪里。我要发布我认为必要的内容:
服务
[Service]
public class DataService : Service
{
public List<MyObjects> MyObjectList { get; private set; }
public IBinder Binder { get; private set; }
public override IBinder OnBind(Intent intent)
{
this.Binder = new DataServiceBinder(this);
return this.Binder;
}
public override void OnCreate()
{
base.OnCreate();
pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), 0);
StartForeground(NotificationID, GetNotification("Started Sync"));
//Do some work here to instantiate and populate the List
}
}
服务活页夹
public class DataServiceBinder : Binder
{
public DataServiceBinder(DataService service)
{
Service = service;
}
public DataService Service { get; private set; }
}
服务连接
public class DataServiceConnection : Object, IServiceConnection
{
public DataService Service { get; private set; }
public DataServiceBinder dataServiceBinder;
public bool IsConnected { get; private set; }
public void OnServiceConnected(ComponentName name, IBinder service)
{
dataServiceBinder = service as DataServiceBinder;
IsConnected = this.dataServiceBinder != null;
Service = dataServiceBinder.Service;
ServiceConnectionChanged?.Invoke(this, true);
}
public void OnServiceDisconnected(ComponentName name)
{
ServiceConnectionChanged?.Invoke(this, false);
Service = null;
}
public event EventHandler<bool> ServiceConnectionChanged;
}
在我的活动中,当我尝试通过服务传递适配器列表时,“服务”为null,因此我得到了null引用异常。为什么我的服务为空?我是否无法正确绑定我的服务?为了记录,它们服务在“应用程序”上下文中启动。
白衣非少年
相关分类