android – 什么时候才能调用有线服务的onServiceConnected?

前端之家收集整理的这篇文章主要介绍了android – 什么时候才能调用有线服务的onServiceConnected?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从这样的另一个服务绑定服务:
public class ServiceA extends Service {
    private ServiceB mDataService;
    private boolean mIsBound;

    @Override
    public void onCreate(){
        super.onCreate();
        doBindService();
        /* ... */
    }

    @Override
    public void onStart(final Intent intent,final int startId){
        /*...*/
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,IBinder service) {            
            mDataService = ((ServiceB.LocalBinder)service).getService();
        }
        public void onServiceDisconnected(ComponentName className) {             
            mDataService = null;
        }
    };

    void doBindService() {          
        bindService(new Intent(ServiceA.this,ServiceB.class),mConnection,Context.BIND_AUTO_CREATE);          
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {                     
            unbindService(mConnection);
            mIsBound = false;
        }
    }       
}

这是我从goolge的样本中获取的一个简单片段:)
代码工作正常,mDataService保存对ServiceB实例的引用,但有一件事我无法理解:在调用onStart之后调用onServiceConnected回调.正如我在android的文档中所看到的那样,the callback is running on the main thread – 但是我可以指望它在我的情况下总是按照这个顺序发生吗? onCreate – > onStart – > onServiceConnected?

解决方法

在官方开发指南中没有明确说明,Context.bindService()确实是一个异步调用,这也解释了为什么ServiceConnection.onServiceConnected()被实现为回调.查看 dev guide

A client can bind to the service by calling bindService(). When it does,it must provide an implementation of ServiceConnection,which monitors the connection with the service. The bindService() method returns immediately without a value,but when the Android system creates the connection between the client and service,it calls onServiceConnected() on the ServiceConnection,to deliver the IBinder that the client can use to communicate with the service.

一旦正确建立了与服务的连接,就会在未来的某个时刻(在调用Context.bindService()之后不立即)在UI线程上调用ServiceConnection.onServiceConnected().

原文链接:https://www.f2er.com/android/316834.html

猜你在找的Android相关文章