安卓之Service详解(三)【安卓IPC之AIDL】

Android BoundService 详解

1.一般实现步骤讲解

在客户端(Activity中)要完成

1.客户端通过BindService()方法来绑定一个服务对象(业务对象)
  如绑定成功会回调ServiceConnection接口方法onServiceConnected()
2.OnServiceConnection()方法的其中一个参数是在Service中OnBind()返回的Binder的实例。
3.通过在OnServiceConnection()方法中接受Binder的实例来调用Binder中返回Service实例的方法,获得Service的实现。
4.通过Service的实例就可以调用Service的的共有方法。

在服务端一般要实现:

1.服务端通过创建一个*.aidl文件来定义一个可以被客户端调用的业务接口
       一个AIDL文件的规范:
       1>不能有修饰符,类似接口的写法
       2>支持数据类型,String\CharSequence\List(存放字符串)\Map\自定义类型
       自定义类型:
       (要实现Parcelable接口,定义一个AIDL文件声明该类型,在其他AIDL中使用该类型需要import包)
2.服务端需要提供一个业务接口的实现类,通常继承 Stub类
3.通过Service的onBind()方法返回被绑定的业务对象

2.例子讲解

先来张图片



接下来我们按照源码一步步分析

1>先上布局文件,activity_main.xml,三个Button,三个点击事件,很简单,不做讲解

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.allan.android_async_http.MainActivity">   
<Button
        android:onClick="boundService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="boundService"/>
    <Button
        android:onClick="unboundService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unboundService"/>
    <Button
        android:onClick="useIPC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="useIPC"/>

</LinearLayout>

2>接下来是客户端MainActivity.java的代码

public class MainActivity extends AppCompatActivity {
    private ICat cat;
    private
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值