Service(五)跨应用绑定 Service并通信(使用AIDL)

跨应用绑定 Service 要 用 AIDL  Android Interface definition language

1.新建一个aidl文件  这个接口当作binder返回。(aidl文件简单记忆成与lib的头文件相似,要把它复制到作用它的项目工程中)

interface AppServiceBinder {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);


    void setData(String dt);
}


2. Service需要返回 IBinder,同一个应用内的service之间用binder,这里也是。

public class AppService extends Service {
    public AppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new AppServiceBinder.Stub(){
           
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {


            }


            @Override
            public void setData(String dt) throws RemoteException {
                AppService.this.data = dt;
            }
        };
    }
...

3.bindService(intent),注意绑定 service时的两个回调函数。onServiceConnected   onServiceDisconnected

 <span style="white-space:pre">	</span>Intent i = new Intent();
        i.setComponent(new ComponentName("com.example.kf8i4fk.appservice","com.example.kf8i4fk.appservice.AppService"));
        switch(v.getId()){
            case R.id.btnStartAppServ:
       <span style="white-space:pre">		</span>break;
            //...
            case R.id.btnBindAppServ:
                bindService(i,this, Context.BIND_AUTO_CREATE);
<span style="white-space:pre">	</span>//...
 
    @Override
    public void <span style="color:#ff0000;">onServiceConnected</span>(ComponentName name, IBinder service) {
        System.out.println("onServiceConnected");
        binder = AppServiceBinder.Stub.asInterface(service);
    }
    
    @Override
    public void <span style="color:#ff0000;">onServiceDisconnected</span>(ComponentName name) {
        System.out.println("onServiceDisconnected");
    }


4.通信

注意其它线程不能直接使用ui线程里的控件更新界面,要用消息队列将数据 发送到ui线程,后者再更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值