我怎么能等待Android服务的`onServiceConnected`回调?

时间:2018-06-08 16:13:19

标签: java android

我知道这个问题已经得到解答,但在我的案例中没有一个解决方案有效。我有一个ContextWrapper类,我试图从那里使用服务。 ContextWrapper应该提供一个使用服务功能返回布尔值的函数,这里是代码:

class SomeContextWrapper extends ContextWrapper {

    private SomeService mService;

    private SomeServiceConnection mConnection = new SomeServiceConnection();

    // Connexion class
    public class SomeServiceConnection implements ServiceConnection
    {
        @Override

        public void onServiceConnected(ComponentName name, IBinder service)
        {
            SomeService.SomeServiceBinder binder = (SomeService.SomeServiceBinder)service;

            mService = binder.getService();
        }

        @Override

        public void onServiceDisconnected(ComponentName name)
        {
            mService = null;
        }
    }

    // Constructor
    public SomeContextWrapper(Context context)
    {
        super(context);

        Intent serviceIntent = new Intent(this, SomeService.class);

        startService(serviceIntent);

        bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

    // Check
    public boolean check(int someData)
    {
        if (mService != null)
        {
            return mService.otherCheck(someData);
        }

        return false;
    }
}

这是调用代码:

...

SomeContextWrapper wrapper = new SomeContextWrapper(this);

for (int someData : someDataArray)
{
    if (!wrapper.check(someData))
    {
        return false;
    }
}

...

问题是:wrapper.check()函数alwats在onServiceConnected回调之前执行,我想避免这种情况,并确保服务连接后再继续。有谁知道解决方案?

以下是我尝试的一些解决方案的列表,正如我所说的,它们都没有正常工作:

How do I wait until a service is actually connected ?

How do you wait for the Activity until the service is linked ?

How do I wait until a service is actually connected ? (Different from first)

感谢您的帮助!

0 个答案:

没有答案