上一篇中介绍了Service的第一种方式,startService,这一篇来讲解一下另一张方式 bindService。

当创建一个能提供绑定功能的服务时,我们必须提供一个IBinder对象,客户端能使用这个对象与服务进行交换。在Android中有三种定义方式:

1、扩展Binder类 (条件:服务和应用在同一个进程当中,是最常见的情况)

2、使用Messager

3、使用AIDL (Android Interface Defination Language)


Bound Services

A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.


这里以扩展Binder类为例讲解如何创建Bound Services.

Binder

extends Object
implements IBinder
java.lang.Object
android.os.Binder
很明显,Binder实现了IBinder这接口。

通过扩展Binder类创建Bound Service的步骤如下:

a、在Service类中,创建一个Binder实例,包含客户端能调用的公共方法,返回当前服务对象;

b、在onBind()方法中返回Binder实例;

c、在客户端,从onServiceConnected方法中获得Binder实例。


工程目录结构:


运行界面:


源代码:

MainActivity.java:

package com.service.activity;import com.service.activity.BinderService.MyBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button btnStartService;private Button btnstopService;private boolean isConnected = false;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btnStartService = (Button)findViewById(R.id.btnStartService);        btnStartService.setOnClickListener(listener);        btnstopService = (Button)findViewById(R.id.btnStopService);        btnstopService.setOnClickListener(listener);    }        private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnStartService:funBindService();break;case R.id.btnStopService:funUnBindService();break;default:break;}}private void funBindService() {Intent intent = new Intent(MainActivity.this, BinderService.class);bindService(intent, conn, Context.BIND_AUTO_CREATE);}private void funUnBindService() {if(isConnected == true){unbindService(conn);}}};private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {isConnected = false;}//与Service连接时被回调@Overridepublic void onServiceConnected(ComponentName name, IBinder iBinder) {MyBinder myBinder = (MyBinder)iBinder;BinderService service = myBinder.getService();service.MyMethod();isConnected = true;}};}

BinderService.java

package com.service.activity;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class BinderService extends Service{private static final String TAG = "BinderService";private MyBinder myBinder = new MyBinder();//内部类,扩展自Binder类public class MyBinder extends Binder{public BinderService getService(){return BinderService.this;}}//复写onBind方法,并且返回IBinder的实现类@Overridepublic IBinder onBind(Intent intent) {Log.i(TAG, "onBind");return myBinder;}public void MyMethod(){Log.i(TAG, "MyMethod");}@Overridepublic boolean onUnbind(Intent intent) {Log.i(TAG, "onUnbind");return super.onUnbind(intent);}@Overridepublic void onDestroy() {Log.i(TAG, "onDestroy");super.onDestroy();}}



main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button     android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="启动service"        android:id="@+id/btnStartService"/><Button     android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="停止service"        android:id="@+id/btnStopService"/></LinearLayout>

点击启动service,日志输出信息:


点击停止service,日志输出信息:



更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. Python list sort方法的具体使用
  3. python list.sort()根据多个关键字排序的方法实现
  4. 编写高效的Android代码
  5. Android语言切换原理
  6. Android之常见安全问题
  7. 初涉Android蓝牙开发(转) 收藏以备后用
  8. 有关Android线程的学习
  9. Android中可以做的两件坏事---破解锁屏密码和获取Wifi密码

随机推荐

  1. Android(安卓)如何获取应用签名,微信需要
  2. Android单元测试/Ui测试+JaCoCo覆盖率统
  3. Android获取不同手机 自身存储和外置SD卡
  4. 以 Okhttp3源码 为例 ------ 图解 缓存机
  5. 【定制Android系统】Android(安卓)O 应用
  6. 微信系列研究之-----资源文件保护的小把
  7. Android自定义主题样式详解(结合自定义tit
  8. 八大Android土鳖设计
  9. 【从零单排】利用科大讯飞语音包实现Andr
  10. android高分段进阶攻略(1)传感器