AIDL(Android 接口定义语言) 是 Android 提供的一种进程间通信 (IPC) 机制。定义客户端与服务使用进程间通信 (IPC) ,进行相互通信时都认可的编程接口。通过这门语言,我们可以在一个进程访问另一个进程的数据,甚至调用它的一些方法,当然,只能是特定的方法。下面直接上代码,代码中每步的注释都很详细。
/*****************************************服务端代码Service***********************************************/
//服务端代码Service,在绑定时会暴露AIDL接口,等待其他应用程序调用
public class MyService extends Service {
public MyService() {
}
//第二步,绑定Service,将胶水涂在Service表面
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return new MyBinder();
}
//第一步,胶水
private class MyBinder extends IMyAidlInterface.Stub {
//AIDL进程接口的回调方法.当其他应用调用时,在这里执行
@Override
public int plus(int value01, int value02) throws RemoteException {
int result = value01 + value02;
return result;
}
}
}
/******************************************客户端**********************************************/
public class MainActivity extends AppCompatActivity implements ServiceConnection{
//服务端的AIDL接口
private IMyAidlInterface iMyAidlInterface;
private EditText editText01,editText02;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText01 = (EditText) findViewById(R.id.et01);
editText02 = (EditText) findViewById(R.id.et02);
textView = (TextView) findViewById(R.id.textview);
}
//第三步绑定服务端的Service
public void bind(View view){
Intent intent = new Intent();
//跟服务端的清单文件的必须相同
intent.setAction("aidl_server");
boolean isBindServer = bindService(intent,this, Context.BIND_AUTO_CREATE);
Toast.makeText(this,"是否绑定成功:" + isBindServer,Toast.LENGTH_SHORT).show();
}
//第五步/调用服务端的AIDL接口
public void callAIDL(View view){
//获取文本输入框的内容
String edit01 = editText01.getText().toString();
String edit02 = editText02.getText().toString();
if(!"".equals(edit01)&&!"".equals(edit02)) {
int editInt01 = Integer.parseInt(edit01);
int editInt02 = Integer.parseInt(edit02);
//在服务端进行逻辑计算,将结果返回客户端展示
try {
int result = iMyAidlInterface.plus(editInt01, editInt02);
textView.setText("结果为:" + result);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
//第四步,绑定成功时,通过服务端表面的胶水间接获取到AIDL接口
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
注:如有问题可以回复,看到第一时间分析解决,码农不易,感觉对您有用,帮助到您,可否打赏一杯可乐,在此谢过诸位,愿诸君终成大神,前程似锦~~~