(1) 先创建一个服务,继承Service类。并在AndroidManifest.xml中进行配置。
(2) 在服务中创建query方法
public String query(String no){
return this.studnets.get(no);
}
(3) 书写内部类,继承Binder类。给出方法getName。
public class StudentManageService extends Service {
private Map<String, String> studnets = new HashMap<String, String>();
@Override
public IBinder onBind(Intent intent) {
this.studnets.put("1", "like");
this.studnets.put("2", "chris");
this.studnets.put("3", "sam");
this.studnets.put("4", "jerry");
return new StudentManage();
}
public String query(String no){
return this.studnets.get(no);
}
private class StudentManage extends Binder implements IStudent{
@Override
public String getName(String no) {
return query(no);
}
}
}
(4) 在页面启动时绑定服务。
Intent service = new Intent(this, StudentManageService.class);
this.bindService(service, conn, BIND_AUTO_CREATE);
(5) 因为绑定服务需要ServiceConnection对象,再书写一个类继承ServiceConnection
private class StudnetConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
student = (IStudent) binder;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
(6) 在点击事件中调用ServiceConnection中返回的IBinder对象。
public void onClick(View v) {
String no = txtNo.getText().toString();
String name = student.getName(no);
lblName.setText(name);
}
(7) 当窗口销毁时,结束服务
protected void onDestroy() {
super.onDestroy();
this.unbindService(conn);
}