android - 为什么我不能从同一个对象两次绑定到我的前台服务?
问题描述
我在应用程序 A 中有一个对象,它实现IServiceConnection
了绑定到Service
不同应用程序(应用程序 B)中的前台:
public class MyServiceConnection : Java.Lang.Object, IServiceConnection
{
private IBinder _binder;
private TaskCompletionSource<bool> _connectTcs;
public MyServiceConnection()
{
BeginConnect();
}
public void BeginConnect() => ConnectAsync().ContinueWith(EndConnect);
public Task<bool> ConnectAsync(CancellationToken ct = default)
{
if (_connectTcs?.IsCompleted ?? true)
{
_connectTcs = new TaskCompletionSource<bool>();
ct.Register(() => _connectTcs.TrySetCanceled(ct));
var package = "com.sample.appb";
var componentName = new Componentname(package, $"{package}.ServiceInB");
var service = new Intent().SetComponent(componentName);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
Application.Context.StartForegroundService(service);
}
else
{
Application.Context.StartService(service);
}
Application.Context.BindService(service, this, Bind.AutoCreate);
}
return await _connectTcs;
}
private void EndConnect(Task task)
{
// handle task result
}
public void OnServiceConnected(ComponentName name, IBinder service)
{
_binder = service;
}
public void OnServiceDisconnected(ComponentName name)
{
_binder = null;
}
// methods that are called on the service
}
创建对象时,我绑定到它Service
并且它是成功的。当应用程序 B 崩溃或我调用am force-stop
应用程序 B 时,OnServiceDisconnected()
会被调用,这是意料之中的。我通过再次连接来处理丢失的连接,但是在第二个连接上OnServiceConnected()
永远不会被调用,所以我永远不会让我的IBinder
对象调用方法。如果我重新启动应用程序 AI 可以再次执行单个绑定。如何Service
在一次运行期间多次正确获取活页夹?
解决方案
为了解决这个问题,我将原始对象拆分为两个对象:一个从服务继承IServiceConnection
并保存IBinder
该服务,另一个保存这些对象的实例。当持有者需要连接时,它首先释放任何持有的 实例IServiceConnection
,然后调用Context.BindService()
一个新实例。当持有者需要断开连接时,它会调用Context.UnbindService()
,然后释放IServiceConnection
实例。
推荐阅读
- reactjs - 访问 token_unidentified
- github - Github 流 QA 和 UAT 测试
- angular - Angular 服务传递整数 url 参数被调用两次,将参数值附加到 API 调用
- flask - Flask,管理数据库连接(无 ORM)
- php - 如何在 Laravel 和 Linux 操作系统中访问公用文件夹的文件
- python - 如何使用编码在字符串中的命名空间创建一个空白对象,例如一个列表?
- ruby - 查找与嵌套 ruby 哈希中的参数匹配的所有值
- ruby-on-rails - 在 users_controller 的每个方法中添加 User.where(organisation_id: current_user.organisation_id) 是否有替代解决方案?
- r - 跳过 facet_wrap 中包含少于 10 个点的图——访问 ggplot 数据点
- unix - 如何将一行文本添加到目录中的多个文件