Android AIDL Service绑定

2014-06-05
浏览
导读:使用bindService方法将如何写呢? 具体的步骤如下: 1. 使用bindService方法启动服务,bindService (Intent service, ServiceConnection conn, int flags) 有三个参数,这里大家可能会对第二个ServiceConnection和最后第三个参数的标识感到陌生,一般在我们调用

  使用bindService方法将如何写呢? 具体的步骤如下:

       1. 使用bindService方法启动服务,bindService (Intent service, ServiceConnection conn, int flags) 有三个参数,这里大家可能会对第二个ServiceConnection和最后第三个参数的标识感到陌生,一般在我们调用bindService时需要一个ServiceConnection获取服务实例以及状态,代码如下

Java代码:
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(ctx, "android123 service connected", Toast.LENGTH_LONG).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(ctx, "android123 service disconnected", Toast.LENGTH_LONG).show();
}
};


        这样,我们在服务的连接和断开时都会收到一个Toast的消息提示,而bindService最后的参数一般使用BIND_AUTO_CREATE 标识自动创建。所以一般我们绑定一个服务,使用下面的代码
  
        bindService(intent, sc, Service.BIND_AUTO_CREATE);
        来启动服务,而解除绑定可以用  unbindService(sc);

        2. 上面说的都是在非具体的Service中进行操作,下面来看看Service需要处理哪些内容:
public boolean onUnbind (Intent intent) //反绑定服务时做清理工作

Java代码:
public boolean onUnbind (Intent intent) //反绑定服务时做清理工作
public void onRebind (Intent intent) //重新绑定时触发
public abstract IBinder onBind (Intent intent) //我们需要返回一个IBinder对象,所以要实现这个抽象方法


        3. 实现onBind方法,这里我们简单的给服务的调用者传递一个Service的实例

Java代码:
public class cwjBinder extends Binder{
cwjService fetchService()
{
return cwjService.this;
}
}


       我们在构造Service时实例化cwjBinder使用cwjBinder binderObj=new cwjBinder();这时我们在onBind()的返回时设置为binderObj而不是null了。

       4. 回到我们调用Service的地方,在ServiceConnection中的  onServiceConnected 方法第二个参数就是我们刚才的IBinder实例了, 该方法原型为  public void onServiceConnected(ComponentName name, IBinder service) ,这时我们可以调用 fetchService方法了。

编程实现Android远程控制PC

[Android的系统移植与平台开发]Sensor HAL

[Android的系统移植与平台开发]Sensor HAL

用ViewPager实现高仿图片左右滑动自动切换

详解android Content Provider[6]