如果服务和访问者之间需要方法调用和传递参数,调用bindservice()和unbindService()方法启动和关闭服务。
绑定:如果service没被创建,那么调用一次onCreate(),然后调用onBind(),
多次绑定时,不会多次调用onBind()
解除绑定:调用unbindService(),然后onDestory().不可以多次调用unbindService()方法解除绑定。
原理:
客户端调用bindService()启动服务-----》服务端向客服端返回一个Ibinder对象----》客户端透过binder对象调用服务端的方法
一个实例:
服务端的代码
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class StudentService extends Service {
private String[] names = {"张帆","拉法基","老子有把杀猪刀"};
private Binder binder = new StudentBinder();
public String query(int no){
if(no>0&&no<4){
return names[no-1];
}else {
return null;
}
}
public IBinder onBind(Intent arg0) {
return binder;
}
private class StudentBinder extends Binder implements IStudent{
public String queryStudent(int no) {
return query(no);
}
}
}
StudentBinder是私有的,所以定义一个接口让客户端透过binder对象调用服务端的方法, Binder实现了 IBinder接口,所以继承Binder即可。
接口:
public interface IStudent {
public String queryStudent(int no);
}
客服端即activity
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
public class MainActivity extends Activity {
private EditText studentno;
private ServiceConnection conn = new StudentServiceConnection();
private IStudent iStudent;
private TextView resultView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView)this.findViewById(R.id.resultView);
studentno = (EditText)this.findViewById(R.id.studentno);
Button button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
Intent service = new Intent(this,StudentService.class);
bindService(service, conn, BIND_AUTO_CREATE);// 客户端调用bindService()启动服务
}
private class StudentServiceConnection implements ServiceConnection{
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
iStudent =(IStudent)arg1;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
iStudent = null;
}
}
protected void onDestroy() {
unbindService(conn);//解除跟服务的绑定
super.onDestroy();
}
private final class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
String no =studentno.getText().toString();
String name = iStudent.queryStudent(Integer.valueOf(no));
resultView.setText(name);
}
}
}