193_AIDL的使用
2016-06-06 22:11
399 查看
AIDL的使用
打个比方,一个A应用要调用另一个B应用的服务的方法假设这个服务就跟支付宝的支付功能一样
MyPayService的pay方法
肯定不能直接调用
那么就要通过代理的方式来调用
这时候就用到AIDL
AIDL
Android Interface Definition Languageandroid接口定义语言
就是用来进程间通信
步骤
我们要在支付应用里面写一个AIDL文件
就是一个接口interface MyPay{
String pay(int money);
}
注意,aidl里面不能有权限修饰符
然后系统就用sdk文件夹里的platform-tools里的aidl.exe
自动帮我们生成了一个代理对象
是在gen目录下的
MyPay.java
我们打开看一下就发现多了很多很多东西
反正我们也看不懂
然后我们看见这个MyPay接口里面
还有一个抽象类
abstract class Stub extends Binder implements MyPay
然后这个aidl文件也拷贝到A应用里面
注意包名也要一样包名一样,aidl文件一样,所以生成的java文件应该也是一样的
现在A应用和B应用都有一样的字节码文件了
然后是PayService
public class MyPayService extends Serivce{public IBinder onBinder(Intent intent){
return new MyPay.Stub(){
public String pay(int money){
return MyPayService.this.pay();
}
};
}
private String pay(int money){
return money;
}
}
注册一下服务
<service android:name=”com.lichhowger.MyPayService”><intent-filter>
<action android:name=”com.mypay.service”/>
</intent-filter>
</service>
然后我们在A应用绑定服务
参数:1.intent
2.ServiceConnection
3.flag
Intent intent=new Intent();
intent.setAction(“com.mypay.service”);
MyPayServiceConnection
4000
connection=new MyPayServiceConnection();
bindService(intent,connection,Service.BIND_AUTO_CREATE);
//自己来个内部类
class MyPayServiceConnection implements ServiceConnection{
public void onServiceConnected(ComponentName name,IBinder service){
//将远程服务传递过来的对象转换为MyPay对象
MyPay mypay=MyPay.Stub.asInteface(service);
}
public void onServiceDisconnected(ComponentName name){
}
}
调用方法
mypay.pay(“99”);
总结
应用B中:
1.要写一个aidl文件2.要写一个服务,然后返回IBinder代理对象
应用A中:
1.要拿到B的aidl文件,生成java字节码文件2.bindService绑定服务
3.写一个ServiceConnection把远程服务传递过来的对象转换成MyPay对象
4.调用方法
相关文章推荐
- Grails用CONSOLE测试,比写集成测试还快
- vector中pair的排序方法
- 196. Delete Duplicate Emails
- [转载] fail-fast总结(通过ArrayList来说明fail-fast的原理、解决办法)
- Rails中force index
- TIME_WAIT状态存在的必要性
- Ex2010-17 Linked Mailbox in Exchange Server
- __stack_chk_fail栈检查失败
- return columns.All(new Func<string, bool>(list.Contains));
- Ex2010-16 Connect Users On Child Domain to Exchange On Root Domain
- scala之trait详解三:延时绑定
- Exchange 2010 PS 之new-mailboxDatabase&Get-MailboxDatabase&Move-databasePath!
- 设计模式笔记-Chain of Responsibility职责链模式
- systemtap分析软raid io拆分问题
- wait(),notify(),notifyAll()进行了详细的分析介绍
- iOS之蓝牙开发—何时触发(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral方法
- hdu 1023 Train Problem II
- 比Android更深远的改变世界——谷歌开源人工智能系统TensorFlow文档中文版
- CF Gym 100685E Epic Fail of a Genie
- Rails中destroy_all和delete_all的差别