跨应用启动service&&AIDL
1、AIDL(android接口定义语言) 是 Android 提供的用于与 Service 进行跨应用、跨进程通信的一种机制,高效、灵活,使用方便。
2、android5.0之前都可以通过配置在manifest里service 的action来启动。android5.0之后都必须使用显示intent。
3、跨应用启动service
- 一个应用manifest
-
<service android:name=".AppService" android:enabled="true" android:exported="true"> </service>
- 另一个启动应用
-
intent = new Intent(); intent.setComponent(new ComponentName("com.example.startservicefromanother", "com.example.startservicefromanother.AppService"));//第一个参数是包名,第二个是类名 startService(intent);
4、跨应用绑定service并通信
-
所有的.aidl文件已经需要传递的对象接口需要在Service 与Client中各一份。并且必须处于相同的包名之下。添加成功之后,clean一下。adt插件会自动生成.java文件。
![]()
![]()
- aidl文件:
-
package com.example.AIDL; interface IAppServiceBinder{ void SetString(String Data); void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,double aDouble, String aString); }
- anotherapp获得binder:
-
private com.example.AIDL.IAppServiceBinder binder = null; @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { //这里不能强制转换,因为虽然类的内容是一样的,但是却不是同一个。(每个app能访问到的毕竟是自己的类) binder = com.example.AIDL.IAppServiceBinder.Stub.asInterface(arg1); }
- startfromanotherapp中的service代码:
-
@Override public IBinder onBind(Intent intent) { return new com.example.AIDL.IAppServiceBinder.Stub() { @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { // TODO Auto-generated method stub } @Override public void SetString(String Data) throws RemoteException { AppService.this.data = Data; } }; }
- 其余的操作无差别。



浙公网安备 33010602011771号