Can bindService() be made to block?

Viewed 16422

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 bound, so I would like to simply wait until the binding is finished before any Activity is started. Is there a way to have the service bound before onCreate() or onResume() is called? I think there might be a way to do the binding in Application. Any ideas?

Edit:

if in onCreate() I do this.

bindService(service, mWebServiceConnection, BIND_AUTO_CREATE);
synchronized (mLock) { mLock.wait(40000); }

The ServiceConnection.onServiceConnected doesn't get called for 40 seconds. It's clear that I have to let onCreate() return if I want the service to bind.

So it appears there's no way to do what I want.

Edit 2: Android how do I wait until a service is actually connected? has some good commentary about what is going on in Android when binding a service.

5 Answers

Android 10 has introduced a new bindService method signature when binding to a service to provide an Executor (which can be created from the Executors).

/**
     * Same as {@link #bindService(Intent, ServiceConnection, int)} with executor to control
     * ServiceConnection callbacks.
     * @param executor Callbacks on ServiceConnection will be called on executor. Must use same
     *      instance for the same instance of ServiceConnection.
    */
    public boolean bindService(@RequiresPermission @NonNull Intent service,
            @BindServiceFlags int flags, @NonNull @CallbackExecutor Executor executor,
            @NonNull ServiceConnection conn) {
        throw new RuntimeException("Not implemented. Must override in a subclass.");
    }

See this Answer

Related