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);

但我的问题是……连接内部有什么?

   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/

4

3 回答 3

16

I would like to point out that if you follow the service examples provided by google then your service will leak memory, see this chaps excellent post on how to do it properly (and vote for the related Google bug)

http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android

于 2011-01-10T12:06:11.863 回答
5

应该避免从 Activity 绑定到服务,因为它会在 Activity 配置更改时引起问题(例如,如果设备旋转,则从头开始重新创建活动,并且必须重新创建绑定)。
请参阅 Commonsware 对以下关于 stackoverflow
与服务中的活动进行通信 (LocalService) - Android 最佳实践的帖子的评论

于 2011-03-17T13:03:17.860 回答
1

To connect a service to an activity, all you need to write in a ServiceConnection implementation is :

@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;
}

Here mBoundService is an object of your bound service. Have a look at this Bound Service Example.

于 2014-11-26T17:08:15.300 回答