Can bindService() be made to block?

前端 未结 4 890
鱼传尺愫
鱼传尺愫 2021-02-13 15:44

I have an Android application that uses a Remote Service and I bind to it with bindService(), which is asynchronous.

The app is useless until the service is

4条回答
  •  北海茫月
    2021-02-13 15:54

    When I need to wait a service to be bound before doing something else I play with locks. Precisely, the ServiceConnection owns a lock object and exposes a waitUntilConnected method that block on the lock until a wake up signal. That notification is located in the onServiceConnected callback.

    public class MyServiceConnection implements ServiceConnection {
    
        private volatile boolean connected = false;
        private Object lock = new Object();
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            connected = true;
    
            synchronized (lock) {
                lock.notifyAll();
            }
        }
    
        @Override
        public void onServiceDisconnected(ComponentName name) {
            connected = false;
        }
    
        public void waitUntilConnected() throws InterruptedException {
            if (!connected) {
                synchronized (lock) {
                    lock.wait();
                }
            }
        }
    
    }
    

    So, for example, if an activity has to wait a service to be bound, it calls simply the waitUntilConnected method.

    protected void onStart() {
        super.onStart();
    
        bindService(myServiceIntent, myServiceConnection, Context.BIND_AUTO_CREATE);
        try {
            myServiceConnection.waitUntilConnected();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    I placed the waitUntilConnected method in onStart just as an example, but it has to be called in a different thread. I'd like to hear a more elegant way! :)

提交回复
热议问题