Android绑定服务(二):创建绑定…

来源:互联网 发布:服务器端口开启 编辑:程序博客网 时间:2024/06/16 16:40
- 核心:提供一个定义了客户端到服务端交互编程接口的IBinder

- 定义接口的三条途径:

-- 扩展Binder类
> 服务归应用私有,且跑在同一个进程
> 实例由onBind()返回
> 若服务仅仅为本应用的后台工作,那么推荐使用
> 除非服务被其它应用或进程调用

-- 使用Messenger
> 接口需要跨进程工作
>Handler:定义在服务中,Messenger基于之而向客户端分享IBinder,使客户端能钩运用消息对象向服务发送命令
> 客户端亦可自定义一个Messenger,这样服务可以回传消息
>这是IPC的最简便途径。Messenger将所有请求排队到同一个线程——这样就无需考虑线程安全问题。
> 基于AIDL实现

-- 使用AIDL
> AIDL: Android Interface DefinitionLanguage
> 将对象解构为操作系统识别的原始类型,跨进成传送、重组以执行IPC
> 同时处理多个请求应处理线程安全问题
>创建.aidl文件以定义接口,安卓SDK工具生成一个实现该接口的抽象类来处理IPC。
> 多数应用无必要使用。

扩展Binder类
- 如何创建?
1. 在服务中创建一个Binder类的实例,以下任一方式皆可:
   >包含供客户端调用的公共方法
   >返回当前服务的实例,它包含客户端可以调用的公共方法
   >返回一个服务包含的内部类的实例,由它提供客户端调用的方法
2. 从onBinder()方法返回这个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();

   

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

   

   
public int getRandomNumber() {
     
return mGenerator.nextInt(100);
   
}
}
3.在客户端,从oonServiceConnected()方法接收到Binder,然后根据需要调用方法。
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;
       
}
   
}

   

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

   

   
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;
       
}
   
};
}
- 关键组件:Service, Binder, ServiceConnection

使用Messenger
- 如何运用Messenger?
1. 服务实现一个Handler来接收从客户端来的回调
2. Handler被用来创建Messenger对象(Handler的引用)
3. Messenger创建onBind()方法返回的IBinder
public class MessengerService extends Service {
   

   
static final int MSG_SAY_HELLO = 1;

   

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

   

   
final Messenger mMessenger = new Messenger(new IncomingHandler());

   

   
@Override
   
public IBinder onBind(Intent intent) {
       
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
       
return mMessenger.getBinder();
   
}
}
4. 客户端使用IBinder来实例化Messenger,用它来向服务发送消息对象
5. 服务的Handler接收到各个消息对象,具体地说,在handleMessage()方法中
- 此方法中,没有供客户端调用的“方法”。取而代之的是由客户端传递消息给服务进行处理
public class ActivityMessenger extends Activity {
   

   
Messenger mService = null;

   

   
boolean mBound;

   

   
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()回调时,向服务端发送一条消息,将客户端的Messenger作为send()方法的replyTo参数

原创粉丝点击