首页 > 解决方案 > 为什么我不能从同一个对象两次绑定到我的前台服务?

问题描述

我在应用程序 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在一次运行期间多次正确获取活页夹?

标签: androidxamarin.androidandroid-service

解决方案


为了解决这个问题,我将原始对象拆分为两个对象:一个从服务继承IServiceConnection并保存IBinder该服务,另一个保存这些对象的实例。当持有者需要连接时,它首先释放任何持有的 实例IServiceConnection,然后调用Context.BindService()一个新实例。当持有者需要断开连接时,它会调用Context.UnbindService(),然后释放IServiceConnection实例。


推荐阅读