2024年4月16日发(作者:)

android 的Activity和Service之间的通信

在android中Activity负责前台界面展示,service负责后台的需要长期运行的任务。

Activity和Service之间的通信主要由IBinder负责。在需要和Service通信的Activity

中实现ServiceConnection接口,并且实现其中的onServiceConnected和

onServiceDisconnected方法。然后在这个Activity中还要通过如下代码绑定服务:

Java代码

1. Intent intent = new Intent().setClass( this , );

2. bindService( intent , this , _AUTO_CREATE );

当调用bindService方法后就会回调Activity的onServiceConnected,在这个方法

中会向Activity中传递一个IBinder的实例,Acitity需要保存这个实例。代码如下:

Java代码

1. public void onServiceConnected( ComponentName inName , IBinder servic

eBinder) {

2. if ( rtClassName().endsWith( "IHRService" ) ) {

3. try {

4. eBinder= serviceBinder;

5. mService = ( (er) serviceBinder).getService();

6. //mTracker = er;

7. } catch (Exception e) {}

8.

9. }

10. }

在Service中需要创建一个实现IBinder的内部类(这个内部类不一定在Service中实

现,但必须在Service中创建它)。

Java代码

1. public class MyBinder extends Binder {

2. //此方法是为了可以在Acitity中获得服务的实例

3. public IHRService getService() {

4. return ;