1 回答
TA贡献1155条经验 获得超0个赞
好的,我找到了解决方案。由于连接到服务是异步的,所以我不能期望适配器能够像这样同步获取数据:
var adapter = new MyDataAdapter(DataServiceConnection.Service.MyObjectList);
相反,我将自己的活动修改为如下所示:
public class MyDataActivity : AppCompatActivity
{
private DataServiceConnection DataServiceConnection;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (DataServiceConnection == null)
{
this.DataServiceConnection = new DataServiceConnection();
}
Intent serviceToStart = new Intent(this, typeof(DataService));
BindService(serviceToStart, this.DataServiceConnection, Bind.AutoCreate);
DataServiceConnection.ServiceConnectionChanged += ServiceConnectionChanged;
SetContentView(Resource.Layout.MyDataLayout);
}
private void ServiceConnectionChanged(object sender, bool isConnected)
{
if(DataServiceConnection.Service == null)
{
return;
}
if(isConnected)
{
var adapter = new MyDataAdapter(DataServiceConnection.Service.MyObjectList);
}
}
protected override void OnResume()
{
var intent = new Intent(this, typeof(DataService));
BindService(intent, DataServiceConnection, Bind.AutoCreate);
base.OnResume();
}
protected override void OnPause()
{
UnbindService(DataServiceConnection);
base.OnPause();
}
我还对服务连接进行了如下修改:
public class DataServiceConnection : Object, IServiceConnection
{
public DataService Service { get; private set; }
public MyDataActivity DataActivity;
public event EventHandler<bool> ServiceConnectionChanged;
public DataServiceConnection(MyDataActivity myDataActivity)
{
DataActivity = myDataActivity;
}
public void OnServiceConnected(ComponentName name, IBinder service)
{
dataServiceBinder = service as DataServiceBinder;
Service = dataServiceBinder.Service;
ServiceConnectionChanged?.Invoke(this, true);
}
public void OnServiceDisconnected(ComponentName name)
{
ServiceConnectionChanged?.Invoke(this, false);
Service = null;
}
}
现在,我的解决方案仅在连接服务时尝试将数据发送到适配器。该解决方案对我有用,希望对其他任何人有帮助。
- 1 回答
- 0 关注
- 125 浏览
添加回答
举报