Android Activity绑定到Service

当一个Activity绑定到一个Service上时,它负责维护Service实例的引用,允许你对正在运行的Service进行一些方法调用。

       Activity能进行绑定得益于Service的接口。为了支持Service的绑定,实现onBind方法如下所示:

java代码:

  1. private final IBinder binder = new MyBinder();
  2. @Override
  3. public IBinder onBind(Intent intent) {
  4. return binder;
  5. }
  6. public class MyBinder extends Binder {
  7. MyService getService()
  8. {
  9. return MyService.this;
  10. }
复制代码


        ServiceActivity的连接可以用ServiceConnection来实现。你需要实现一个新的ServiceConnection,重写onServiceConnected和onServiceDisconnected方法,一旦连接建立,你就能得到Service实例的引用。

java代码:

  1. // Reference to the service
  2. private MyService serviceBinder;
  3. // Handles the connection between the service and activity
  4. private ServiceConnection mConnection = new ServiceConnection()
  5. {
  6. public void onServiceConnected(ComponentName className, IBinder service) {
  7. // Called when the connection is made.
  8. serviceBinder = ((MyService.MyBinder)service).getService();
  9. }
  10. public void onServiceDisconnected(ComponentName className) {
  11. // Received when the service unexpectedly disconnects.
  12. serviceBinder = null;
  13. }
  14. }; 
复制代码


        执行绑定,调用bindService方法,传入一个选择了要绑定的Service的Intent(显式或隐式)和一个你实现了的ServiceConnection实例,如下的框架代码所示:

java代码:

  1. @Override
  2. public void onCreate(Bundle icicle) {
  3. super.onCreate(icicle);
  4. // Bind to the service
  5. Intent bindIntent = new Intent(MyActivity.this, MyService.class);
  6. bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
复制代码


        一旦Service对象找到,通过onServiceConnected处理函数中获得serviceBinder对象就能得到它的公共方法和属性。

       Android应用程序一般不共享内存,但在有些时候,你的应用程序可能想要与其它的应用程序中运行的Service交互。

       你可以使用广播Intent或者通过用于启动Service的Intent中的Bundle来达到与运行在其它进程中的Service交互的目的。如果你需要更加紧密的连接的话,你可以使用AIDL让Service跨越程序边界来实现绑定。AIDL定义了系统级别的Service的接口,来允许Android跨越进程边界传递对象。

 

sourceurl:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=98881

原文地址:https://www.cnblogs.com/hnrainll/p/2824269.html