先上图,根据自己理解画的,不足之处,欢迎指正
理解及需要注意的地方,学习资料网上都有
1.aidl文件里,如果引用了自定义的类实例,则必须手动import该类jar包,否则无法自动生成该 aidl的java文件,导致报错
2.客户端和服务端的aidl文件,必须包名和类名以及内容完全相同(是客户端和服务端通信的接口)
3.(1)隐式启动
<service Android:name=".service">
<intent-filer>
<action android:name="com.android.service"/>
<intent-filer>
</service>
final Intent serviceIntent=new Intent();
serviceIntent.setAction("com.android.service");
(2)显示启动
final Intent serviceIntent=new Intent(this,service.class);
startService(serviceIntent);
如果在同一个包中。两者都可以用。在不同包时。只能用隐式启动
4.aidl一般是两个app之间进行通信,所以只能用隐式启动service,但因为Android5.0中service的intent一定要显性声明,当这样绑定的时候不会报错。所以需要找方法将隐性调用变成显性调用。
加上此方法:
public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
// Retrieve all services that can match the given intent
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
// Make sure only one match was found
if (resolveInfo == null || resolveInfo.size() != 1) {
return null;
}
// Get component info and create ComponentName
ResolveInfo serviceInfo = resolveInfo.get(0);
String packageName = serviceInfo.serviceInfo.packageName;
String className = serviceInfo.serviceInfo.name;
ComponentName component = new ComponentName(packageName, className);// Create a new intent. Use the old one for extras and such reuse
Intent explicitIntent = new Intent(implicitIntent);
// Set the component to be explicit
explicitIntent.setComponent(component);
return explicitIntent;
}
绑定时这样设置:
Intent intent=new Intent();
intent.setAction("com.wm.service.AIDLService");//服务端service的manifest中的隐式action
Intent eintent = new Intent(createExplicitFromImplicitInten(this,intent));
MAIDLActivity.this.bindService(eintent, mConnection,Service.BIND_AUTO_CREATE);
最后上代码,已测试,可用。不过用的数据库框架是OrmLite,我的另一篇中有简单学习demo