在service中,我们使用刚刚生成的ICalculateAIDL.Stub静态抽象类创建了一个Binder对象,实现了其中有关计算的业务方法,并在onBind方法中返回它。另外我们还需要在manifest文件中对该服务进行注册:
<service
android:name=".CalculateService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.cqumonk.adil.calculate"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
这时候,我们的服务端工作就完成了。我们开始编写客户端的代码来调用这个服务。首先,我们定义一个activity,包含四个按钮:
然后我们可以在activity中启动之前定义好的service并调用它所提供的服务:
public class MainActivity extends Activity implements View.OnClickListener {
Button mBind;
Button mUnbind;
Button mAdd;
Button mMinus;
TextView txt_res;
private static final String TAG="CLIENT";
private ICalculateAIDL mCalculateAIDL;
private boolean binded=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBind= (Button) findViewById(R.id.btn_bind);
mUnbind= (Button) findViewById(R.id.btn_unbind);
mAdd= (Button) findViewById(R.id.btn_add);
mMinus= (Button) findViewById(R.id.btn_minus);
txt_res= (TextView) findViewById(R.id.txt_res);
mBind.setOnClickListener(this);
mUnbind.setOnClickListener(this);
mAdd.setOnClickListener(this);
mMinus.setOnClickListener(this);
}
@Override
protected void onStop() {
super.onStop();
unbind();
}
private void unbind(){
if (binded){
unbindService(mConnection);
binded=false;
}
}
@Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.btn_bind:
Intent intent=new Intent();
intent.setAction("com.cqumonk.adil.calculate");
bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
break;
case R.id.btn_unbind:
unbind();
break;
case R.id.btn_add:
if(mCalculateAIDL!=null){
try {
int res=mCalculateAIDL.add(3,3);
txt_res.setText(res+"");
} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this,"please rebind",Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_minus:
if(mCalculateAIDL!=null){
try {
int res=mCalculateAIDL.minus(9,4);
txt_res.setText(res+"");
} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this,"please rebind",Toast.LENGTH_SHORT).show();
}
break;
}
}
private ServiceConnection mConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG,"connect");
binded=true;
mCalculateAIDL=ICalculateAIDL.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG,"disconnect");
mCalculateAIDL=null;
binded=false;
}
};
}
当我们点击绑定按钮,观察日志:
点击加法和减法按钮,都可以完成计算并返回值。然后点击解绑按钮: