绑定服务-Bound Services

原文地址:http://developer.android.com/intl/zh-CN/guide/components/bound-services.html

绑定服务-Bound Services

快速浏览


  • 绑定服务允许其他组件绑定它,为了能够与其互动,并执行进程间通信

  • 当所有的客户端被解绑时,绑定服务被摧毁,除非那个服务还在运行。

本文内容


基础知识-The Basics

创建绑定服务-Creating a Bound Service

扩展binder类-Extending the Binder class
使用一个消息传递器-Using a Messenger

绑定到服务-Binding to a Service
管理绑定服务的生命周期-Managing the Lifecycle of a Bound Service

关键类


Service
ServiceConnection
IBinder

范例


RemoteService
LocalService

其它


服务-Services

一个绑定的服务是客户服务器接口上的一个服务器。一个绑定的服务允许组件(如:活动)来绑定一个服务,传送请求,接收响应,甚至执行进程间的通信(IPC)。绑定服务通常只生存在其服务于另一个程序组件时,并且不会无限期的在后台运行。

这篇文章将向你展示怎么创建一个绑定服务,包括怎么样从其他应用程序组件绑定到服务。然而你也应该查看服务-Services文档,更多关于普通情况下服务的额外信息,如怎么从一个服务传递通知,设备服务在前台运行等。

基础知识-The Basics

绑定服务是一个Service类的一个实现,允许其它服务绑定到它并与其互动。为服务提供绑定,你必须实现onBind()回调方法。这个方法返回一个IBinder对象,它定义了程序接口,用户可以用其与服务交互。

一个客户可以通过调用bindService()来绑定到一个服务。当这么做时,必须提供一个ServiceConnection的实现,它监视着与服务的连接。bindService()方法立刻返回了一个空值。但是当Android系统在用户和服务器之间创建一个连接时,它将会在ServiceConnection上调用onServiceConnected()方法来传递IBinder对象,使用户可以与服务通信。

多个用户可以同时连接到一个服务。但是,系统只以第一个用户绑定时调用onBind()方法来获得IBinder对象。然后,系统将同一个IBinder对象传递给后续绑定的客户,并不会重新调用onBind()方法。

当最后一个用户从服务上解绑时,系统摧毁这个服务(除非这个服务由startService())。

当你实现绑定服务时,最重要的就是定义onBind()回调方法返回的接口。你可以使用有一些不同的方法来定义服务的IBinder接口,接下来的章节将讨论每一项技术。

创建绑定服务-Creating a Bound Service

绑定到一个启动的服务

如同在服务-Services文档中讨论的,你可以创建一个服务,同时是被启动的和被绑定的。也就是说,服务可以通过调用startService()被启动,其允许服务无限期的运行,同时也允许一个用户通过调用bindService()方法绑定到服务。

如果你允许服务被启动和被绑定,那么,当服务被启动时,系统在所有用户解绑时不会摧毁这个服务。而是,你必须明确的调用stopSelf()stopService()方法来停止服务。

虽然,通常情况下,你应该实现onBind()onStartCommand()方法,但是,有时必须同时实现两个方法。例如,一个音乐播放器可能会需要无限期的运行,同时提供绑定。通过这种方法,活动可以启动这个服务来播放音乐,并且音乐可以持续播放,即使用户离开了这个应用程序。那么,当用户返回这个应用程序时,活动可以绑定到服务来重新获得播放的控制。

请确认仔细阅读了关于管理绑定服务生活周期-Managing the Lifecycle of a Bound Service的章节,查看更多关于当添加绑定到一个启动的服务时服务生命周期的信息。

当创建一个提供了绑定的服务时,你必须提供一个IBinder来提供程序接口,用户可以用这个接口与服务交互。有三种方法可以用来定义这个接口:

扩展binder类-Extending the Binder class

如果你的服务只对你自己的应用程序私用,并且作为客户在同一个进程中运行(这种情况很常见),你应该通过扩展 Binder类来创建你的接口并且从 onBind()运行一个实例。客户接收 Binder并直接使用它来接入 Binder实现,甚至 Service中可用的公共方法。

当服务对于你的应用程序几乎是运行于后台时,这是首选技术。这种情况下,唯一一个你不建立自己接口的原因是你的服务被其他应用程序所用或使用了多个分开的进程。

使用一个消息传递器-Using a Messenger

如果你想让你的接口在多个不同的进程间工作,你可以为服务创建一个带有 Messenger的接口。在这种情况下,服务将定义一个 Handler来响应不同类型的 Message对象。这个 HandlerMessenger的基础,它可以与客户共享一个 IBinder,允许客户使用 Message对象向服务发送指令。以此,客户可以定义一个属于自己的 Messenger,这样,服务就可以把消息传递回来。

这是最简单的执行进种间通信(IPC)的方法,因为 Messenger队列所有的请求到一个单独的线程当中,所以你不需要设计你的服务为线程安全(thread-safe)

使用AIDL

AIDL(Android接口定义语言-Android Interface Definition Language)执行了把一个对象分解到操作系统能理解的基元,并安排它们到各个进程间来完成IPC等所有工作。前文中提到的技术,使用一个 Messenger(消息传送器)就是基于AIDL和其下面的结构。如前所述, Messenger创建了一个队列,把所有的请求都放在一个线程中,所以服务一次只接收一个请求。然而,如果想你的服务同时接收多个请求,那么你可以直接创建AIDL。在这种情况下,你的服务必须有能力执行多个纯程,并且为线程安全。

为了直接使用AIDL,你必须创建一个.aidl文档,其定义了编程接口。Android SDK工具包使用这个文件来生成一个抽象类,并实现了那个接口来处理IPC。你可以在你的服务中扩展使用。

  • 注解:大多数应用程序不应该使用AIDL来创建一个绑定服务,因为它可能要求能够支持多线程,其结果将会是很复杂的实现。例如,AIDL不适用于大多数应用程序,这篇文档并不讨论怎样使用。如果你确定你需要AIDL,请见AIDL文档。

扩展binder类-Extending the Binder class

如果你的服务只被本地应用程序所使用,并且不需要在多个进程间工作,那么你可以实现你自己的Binder类,让你的客户可以直接接入方法中的公共方法。

  • 注解:这个方法只有在客户和服务在同一个应用程序和进程中时才可行,这种情况很常见。例如,这个方法对于一个音乐应用程序将会非常有用,它需要绑定一个活动到它自己的服务用来以后台播放音乐。

以下为如何设定这个binder类:

1.在你的服务中,创建一个Binder类的实例,实现以下功能之一:

  • 包含客户可以调用的公共方法
  • 返回当前Service的实例,其包含了用户可以访问的公共方法
  • 或返回这个服务包含的另一个类,并含有客户可以访问的公共方法

2.从onBind()回调函数返回这个Binder的实例。

3.在客户端,从onServiceConnected()回调方法接收这个Binder,并用提供的方法来调用绑定服务。

  • 注解:服务和客户端必须在同一个应用程序中的原因是客户端可以计算返回的对象并恰当的调用其APIs。服务和客户端也必须在同一个线程的原因是这种技术不能执行线程间操作。

例如,以下为一个为客户端提供了通过Binder实现接入服务中方法的服务范例:

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();
 
    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
 
    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
}

LocalBinder为客户端提供了getService()方法来取得当前的LocalService实例。这个允许客户端调用服务中的公共方法。例如,客户端可以从服务中调用getRandomNumber()


以下为,当一个按钮被点击时,一个绑定到LocalService的活动并调用getRandomNumber()方法:

public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
 
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
 
    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }
 
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {
 
        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }
 
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

以上范例中展示了客户端怎样通过使用一个ServiceConnection的实现和onServiceConnected()回调方法绑定到一个服务。后续章节中提供了更多的关于绑定到服务流程的信息。

更多实例代码,请见ApiDemosLocalService.javaLocalServiceActivities.java类。

使用一个消息传递器-Using a Messenger

对比AIDL

当你需要执行IPC时,为你的接口使用一个Messenger比用AIDL实现简单,因为[Messenger]把所有对此服务的调用都排在一个队伍中,而单纯的AIDL接口不断的各服务发送请求,这样就要求此服务具备处理多线程的能力。

对于大多数应用程序,服务并不需要执行多线程,所以,使用一个Messenger允许服务在同一时间只处理一个调用。如果处理多线程对你的服务很重要,那么,你应该使用AIDL来定义你的接口。

如果你需要你的服务能够与远程进程通信,那么你可以使用一个Messenger为你的服务提供接口。这个方法允许你执行进程间通信(IPC)而不需要使用AIDL。

以下为怎么样使用Messenger的总结:

  • 服务实现了一个Handler,用来接收每一次调用从客户端返回的回调方法。

通过这种方法,在服务端没有客户端能调用的“方法”。而是,客户传递“消息”(Message对象),同时服务在其Handler中接收。

以下为服务使用一个Messenger接口的简单范例:

public class MessengerService extends Service {
    /** Command to the service to display a message */
    static final int MSG_SAY_HELLO = 1;
 
    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
 
    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    final Messenger mMessenger = new Messenger(new IncomingHandler());
 
    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}


注意Handler中的handleMessage()方法,服务在其中接收进入的Message,基于what成员,决定下一步的做法。


客户端所需做的只是基于服务返回的IBinder创建一个Messenger并使用send()方法发送一条消息。例如,以下为一个简单的活动范例,其绑定到了服务,并向服务传递了MSG_SAY_HELLO消息:

public class ActivityMessenger extends Activity {
    /** Messenger for communicating with the service. */
    Messenger mService = null;
 
    /** Flag indicating whether we have called bind on the service. */
    boolean mBound;
 
    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            mService = new Messenger(service);
            mBound = true;
        }
 
        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mBound = false;
        }
    };
 
    public void sayHello(View v) {
        if (!mBound) return;
        // Create and send a message to the service, using a supported 'what' value
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
 
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
}


注意这个范例中并没有展现服务将怎样响应客户端。如果你希望服务做出反应,那么你需要在客户端创建一个Messenger当客户端接收到onServiceConnected()回调方法,它发送一条Message到服务,其中包括了客户端的Messenger,其存放在在send()replyTo参数之中。

你可以在MessengerService.java(服务端)和MessengerServiceActivities.java(客户端)提供双向通信,具体请见相关范例程序。


绑定到服务-Binding to a Service

应用程序组件(客户端)可以通过调用bindService()方法绑定到一个服务。Android系统将调用服务的onBInd()方法,返回一个IBinder用来与服务交互。

这个绑定是不同步的。bindService()立即返回,但并没有返回[IBinder]给用户。为了接收IBinder,客户端必须创建一个ServiceConnection的实例,并传递给bindService()ServiceConnection包含了一个回调方法,系统调用它来传递IBinder

  • 注解:只有活动(activities),服务(services),和内容提供者(content providers)可以绑定到一个服务——你不能从一个广播接收器(broadcast receiver)绑定到一个服务。

所以,从你的客户端绑定到服务,你必须:

1.实现ServiceConnection

你的实现必须复写两个回调方法:
onServiceConnected()
系统调用这个方法来传递由服务端的 onBind()方法返回的 IBinder
onServiceDisconnected()
当与服务的连接发生了不可预期的丢失,Android系统调用这个方法,例如,服务发生了冲突或被杀死。在服务被解绑时并不会调用这个方法。

2.调用bindService(),传递ServiceConnection的实现。

3.当系统调用onServiceConnected()回调方法时,你可以开始使用由接口定义的方法调用服务。

4.与服务解决连接,调用unbindService()

当客户端被摧毁,它将会从服务解绑,但你应该始终在结果与服务的交互或当你的活动暂停时解绑,这样系统可以在不被使用时关闭。(后续文章将更加具体讨论适当的绑定和解绑时间。)

例如,以下的范例小片断,使客户端连接到使用前文讨论的扩展binder类-Extending the Binder class方法创建的服务,所以,唯一需要做的就是把返回的IBinder传递给LocalService类,并请求LocalService的实例:

LocalService mService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Because we have bound to an explicit
        // service that is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }
 
    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "onServiceDisconnected");
        mBound = false;
    }
};

使用这个ServiceConnection,客户端可以通过把其传递到bindService()来绑定到一个服务。如:

Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

  • bindService()的第一个参数,是一个Intent,其明确的指出了被绑定服务的名字(intent被认为可以暗示性的指出)。

补充注释-Additional Notes

以下为绑定到一个服务时的几个重要的注意事项:

  • 你应该始终捕获DeadObjectException异常,这个异常在连接断开时被抛出。在这远程方法唯一会抛出的异常。
  • 对象为进程引用数。
  • 在客户端生命周期的创建和摧毁时刻,你应该成对使用绑定和解绑。例如:
    • 当你的活动可见时,如果你需要做的只是与服务交互,你应该在onStart()中绑定,在onStop()中解绑。
    • 如果你希望即使活动在后台停止时也接收响应,那么你可以在onCreate()方法中绑定,并在onDestroy()方法中解绑。需要注意的是,这个实现使得你的活动需要在所有服务运行的时候占用该服务(即使在后台运行时)。所以,如果服务存在于另一个进程中,那么你增加了进程的比重,因此,系统也将更有可能性将其杀死。

  • 注解:通常情况下,你不应该在活动的onResume()onPause()方法中绑定与解绑,因为这些回调方法发生在生命周期转换的时候,你应该把此期间的发生的进程减小到最少。同样,如果有多个活动绑定到同一个服务,两个活动间必然存在着转换,当当前的活动在下一个活动绑定(在resume期间)之前,进行解绑(在pause期间),服务可能会被摧毁或重新创建。(这个活动转换中,关于活动如何协调其生命的情况,在Activities)文档中做了详细的表述。

更多的关于怎么样绑定服务的范例代码,请见ApiDemos中的RemoteService.java类。




管理绑定服务的生命周期-Managing the Lifecycle of a Bound Service

service_binding_tree_lifecycle.png
图1.服务的生命周期被启动,并允许绑定。

当一个服务从所有客户端解绑,Android系统将将其摧毁(除非这个活动被onStartCommand()启动)。这样,如果你的服务只是纯粹一个绑定服务,那么你不需要自己管理其生命周期——Android系统将根据其是否被绑定到客户端,来管理其生命周期。

然而,如果你选择实现int, int) onStartCommand()回调方法,那么你必须明确的停止这个服务,因为服务现在被认为已被启动。在这种情况下,服务将一些运行,直到它被自身的stopSelf()方法停止,或其它活动组件调用stopService()方法,而不考虑其是否绑定到客户端。

此外,如果你的服务被启动,并接收绑定,那么当系统调用了onUnbind()方法,你可以有选择性的返回true,如果你希望下一次一个客户端绑定到服务时接收一个onRebind()方法调用(而不是接收一个onBind()调用)。onRebind()返回一个空值,但客户端依然可以接收到onServiceConnected()回调方法中的IBinder。图1展示了这种服务生命周期的逻辑。

更多关于一个启动的服务的信息,请见Services文档。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值