aidl的简单使用
2016-01-22 23:14
323 查看
aidl–进程间的通信(就是2个app之间的通讯)
app1–表示服务的提供者–例如支付包的支付方法,需要对外暴露,让其他app调用其功能
创建一个AliPay.aidl文件–将java的后缀改为aidl
注意:aidl中是不能有修饰符的,否则报错
在app1中的AliPayService 中
在清单文件中
这样就将app1中服务的方法通过aidl暴露出去了
app2—表示服务的使用者—例如美团等等,需要使用支付宝的支付功能
使用方法—需要将app1提供的aidl拿到–注意:包名必须与app1中的包名保持一致
在app2的MainActivity中
注意:给服务绑定后,需要在onDestroy()解除绑定
app1–表示服务的提供者–例如支付包的支付方法,需要对外暴露,让其他app调用其功能
创建一个AliPay.aidl文件–将java的后缀改为aidl
interface AliPay { String pay(float menoy); }
注意:aidl中是不能有修饰符的,否则报错
在app1中的AliPayService 中
public class AliPayService extends Service { @Override public IBinder onBind(Intent intent) { return new AliPay.Stub() { @Override public String pay(float menoy) throws RemoteException { return AliPayService.this.pay(menoy); } }; } public String pay(float menoy ){ return "您支付"+menoy+"元成功"; } }
在清单文件中
<service android:name="com.itheima.zhifubao.AliPayService" > <intent-filter> <action android:name="alipay.pay" /> </intent-filter> </service>
这样就将app1中服务的方法通过aidl暴露出去了
app2—表示服务的使用者—例如美团等等,需要使用支付宝的支付功能
使用方法—需要将app1提供的aidl拿到–注意:包名必须与app1中的包名保持一致
在app2的MainActivity中
public class MainActivity extends Activity { private MyServiceConnection conn; private AliPay aliPay; private String pay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 开启Alipay服务 Intent service = new Intent("alipay.pay"); conn = new MyServiceConnection(); bindService(service, conn, BIND_AUTO_CREATE); } class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { aliPay = AliPay.Stub.asInterface(service); Toast.makeText(MainActivity.this, "绑定成功", Toast.LENGTH_SHORT) .show(); } @Override public void onServiceDisconnected(ComponentName name) { } } public void click(View v) { if (aliPay != null) { try { pay = aliPay.pay(123.23f); } catch (RemoteException e) { e.printStackTrace(); } Toast.makeText(MainActivity.this, pay, Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { super.onDestroy(); if (conn != null) unbindService(conn);// 解绑操作 } }
注意:给服务绑定后,需要在onDestroy()解除绑定
相关文章推荐
- B. Longtail Hedgehog
- 人工智能
- [Errno 111] Connection refusedfailed to upload ker
- wait和waitpid的区别
- 僵尸进程 wait waitpid
- 59. Contains Duplicate II
- [转载]Vertica “ERROR: Too many ROS containers exist”
- zabbix监控磁盘RAID的discover模板
- hdu4300 Clairewd’s message 扩展KMP
- sendmail发件人邮箱设定命令
- 深入浅出设计模式(十二):18.职责链模式(Chain of Responsibility)19.状态模式(State)20.解释器模式(Interpreter)
- Mac os x captain 10.11.1 安装boost库 及配置Xcode
- saiku导出excel单元格格式与中文列宽自动适应
- DS5020 Lun与AIX 系统之间对应关系查看
- 【sphinx】sphinxTrain文档笔记
- 【Leetcode】219. Contains Duplicate II
- 【Leetcode】217. Contains Duplicate
- lightoj1021- Painful Bases
- Metaio SDK camera stream rendering cannot work without passing "-force-opengl" to the executable
- Hdu 1789 Doing Homework again