aidl 全称 android interface definition language( 接口定义语言 )
aidl的写法跟javainterface的写法基本一致,不同的是,aidl不能用public修饰,源代码要以.aidl结束.
aidl的包名跟我们java源代码的包名是一样的.
android studio建立aidl文件:
鼠标在java文件是上右键选择aidl,AS会自动给你创建一个aidl文件.
aidl:
// IService.aidl
package com.lss.alipay;
// Declare any non-default types here with import statements
//不能加public修饰interface,因为其本身就是public的
interface IService {
void callALiPayService();
}
service:
public class ALiPayService extends Service {
private static final String TAG = "ALiPayService";
private class MyBinder extends IService.Stub{
@Override
public void callALiPayService() throws RemoteException {
methodInService();
}
}
private void methodInService(){
Log.d(TAG, "开始付费,购买装备");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "绑定支付宝,准备付费");
return new MyBinder();
}
@Override
public void onCreate() {
Log.d(TAG, "调用支付宝成功");
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "关闭支付宝");
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "取消付费");
return super.onUnbind(intent);
}
}
注意:在服务中写aidl时可能会找不到,这时你需要clean以下代码.
另一个应用调用aidl.
首先把你想调用的那个应用程序的aidl文件拷贝到自己的应用下,包名要一致.
现在开启服务调用aidl
MainActivity:
public class MainActivity extends AppCompatActivity {
private IService iService;
private MyConn conn;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent();
intent.setAction("com.lss.alipay");
//在5.0及以上版本必须要加上这个
intent.setPackage("com.lss.alipay");
}
//按钮点击事件
public void bind(View view){
conn=new MyConn();
bindService(intent,conn,BIND_AUTO_CREATE);
}
public void call(View view){
try {
iService.callALiPayService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void unbind(View view){
unbindService(conn);
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iService=IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
如果你的手机是5.0及以上版本,开启服务时需要明确应用的包名,调用intent的setPackage( String package )方法
//在5.0及以上版本必须要加上这个
intent.setPackage("com.lss.alipay");
不然会报错.错误如下
