AIDL的简单实现
//AIDL
interface IMyAidlInterface {
int plus(int plus01, int plus02);
}
//service
public class PlusService extends Service {
public PlusService() {
}
// 创建
@Override
public void onCreate() {
super.onCreate();
Log.d("1507", "Service onCreate");
}
// 1、创建胶水类
// stub:本意为存根。AIDL提供的类似于胶水的类,在这个胶水中实现了加法运算
private static class MyBinder extends IMyAidlInterface.Stub {
@Override
public int plus(int plus01, int plus02) throws RemoteException {
return plus01 + plus02;
}
}
// 绑定
@Override
public IBinder onBind(Intent intent) {
Log.d("1507", "Service onBind");
return new MyBinder();
}
// 解绑
@Override
public boolean onUnbind(Intent intent) {
Log.d("1507", "Service onUnbind");
return super.onUnbind(intent);
}
// 销毁
@Override
public void onDestroy() {
Log.d("1507", "Service onDestroy");
super.onDestroy();
}
}
<intent-filter>
<action android:name="bind_server"/>
</intent-filter>
//客户端
/**
* 3、绑定服务端的Service
* 4、通过ServiceConnection接口确定是否连接成功
* 5、如果连接成功,调用Service的操作
*/
public class MainActivity extends AppCompatActivity implements
View.OnClickListener, ServiceConnection {
// 自定义Action
public static final String ACTION_BIND = "bind_server";
protected EditText mPlus01Et;
protected EditText mPlus02Et;
protected Button mCalculateBtn;
protected TextView mResultTv;
private IMyAidlInterface mPlusInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("1507", "Activity onCreate");
super.setContentView(R.layout.activity_main);
initView();
bindService();
}
// 绑定Service
private void bindService() {
Intent intent = new Intent(ACTION_BIND);// action
intent.setPackage("net.bwie.aidlserver");// server端对应的包名
boolean isBindSuccessful = bindService(intent, this, Context.BIND_AUTO_CREATE);
Toast.makeText(this, "" + isBindSuccessful, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.calculate_btn) {
int plus01 = Integer.parseInt(mPlus01Et.getText().toString());
int plus02 = Integer.parseInt(mPlus02Et.getText().toString());
// 调用AIDL接口中的方法
try {
int result = mPlusInterface.plus(plus01, plus02);
mResultTv.setText("结果是:" + result);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private void initView() {
mPlus01Et = (EditText) findViewById(R.id.plus01_et);
mPlus02Et = (EditText) findViewById(R.id.plus02_et);
mCalculateBtn = (Button) findViewById(R.id.calculate_btn);
mCalculateBtn.setOnClickListener(MainActivity.this);
mResultTv = (TextView) findViewById(R.id.result_tv);
}
// 绑定成功
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
// 将IBinder用AIDL独有的方式转换为自定义胶水(AIDL接口)
mPlusInterface = IMyAidlInterface.Stub.asInterface(iBinder);
}
// 绑定未成功
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("1507", "Activity onDestroy");
}
}

浙公网安备 33010602011771号