package com.xiazdong.bindservice; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText op1,op2; private Button button; private TextView result; private IAddOp binder ;//使用接口IAddOp private ServiceConnection conn = new AddOpServiceConnection(); private OnClickListener listener = new OnClickListener(){ @Override public void onClick(View v) { int number = binder.addOpService(Integer.parseInt(op1.getText().toString()), Integer.parseInt(op1.getText().toString())); result.setText("result="+number+""); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); op1 = (EditText)this.findViewById(R.id.op1); op2 = (EditText)this.findViewById(R.id.op2); result = (TextView)this.findViewById(R.id.result); button = (Button)this.findViewById(R.id.button); button.setOnClickListener(listener); Intent service = new Intent(this,AddOpService.class); this.bindService(service, conn, BIND_AUTO_CREATE); } private class AddOpServiceConnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) {//绑定服务时调用 binder = (IAddOp)service; } @Override public void onServiceDisconnected(ComponentName name) {//解绑定服务时调用 binder = null; } } }
package com.xiazdong.bindservice; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class AddOpService extends Service { private IBinder binder = new AddOpBinder(); public int add(int a,int b){ //服务提供的方法 return a+b; } @Override public IBinder onBind(Intent intent) { return binder; } private class AddOpBinder extends Binder implements IAddOp{ public int addOpService(int a, int b) { //binder对外暴露一个API调用服务提供的方法 return add(a,b); } } }
package com.xiazdong.bindservice; public interface IAddOp { public int addOpService(int a,int b); }