如何在Android中绑定此服务?

9

这是我Activity中的代码。先初始化一个Intent,然后再建立一Connection,对吗?

hello_service = new Intent(this, HelloService.class);
hello_service_conn = new HelloServiceConnection();
bindService( hello_service, hello_service_conn, Context.BIND_AUTO_CREATE);

但我的问题是...Connection里面应该放什么?

   class HelloServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className,IBinder boundService ) {

        }
        public void onServiceDisconnected(ComponentName className) {

        }
    };

请问在onServiceConnectedonServiceDisconnected中我需要放置什么代码?

我只是想建立一种基本连接,这样我的ActivityService可以相互通信。

编辑:我找到了一个好的教程,现在我可以关闭这个问题,除非有人想回答。 http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-iii-android-services/

3个回答

16

3
这篇文章的链接不可用,但可以在以下网址找到: http://www.mongrel-phones.com.au/default/how_to_make_a_local_service_and_bind_to_it_in_android - Bernd
链接已失效。 - ParikshitSinghTomar

5

1
要将服务连接到活动,您只需要在ServiceConnection实现中编写以下内容:
@Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyBinder myBinder = (MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}

这里的 mBoundService 是您绑定服务的对象。请查看绑定服务示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接