查询学号的简单例子
交互图
service代码
package cn.wonder.studertno;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
/**
* 服务代码
* @author Administrator
*
*/
public class StudentService extends Service{
private String[] names = {"张三","李四","王五","赵六","钱七"};
private IBinder iBinder = new StudentBinder();
public String query(int no) {
if(no>0 && no<6) {
return names[no-1];
}else {
return "只能查询学号1-5的学生";
}
}
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
//此为私有
private class StudentBinder extends Binder implements IStudent{
@Override
public String queryStudent(int no) {
return query(no);
}
}
}
Main代码
package cn.wonder.studertno;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//客户端
public class MainActivity extends ActionBarActivity {
private EditText studentno;
private StudentServiceConnection conn = new StudentServiceConnection();
private IStudent iStudent;
private TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.export);
studentno = (EditText) findViewById(R.id.studentno);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//得到输入的学号
String no = studentno.getText().toString();
String name = iStudent.queryStudent(Integer.parseInt(no));
resultView.setText(name);
}
});
/*
* 激活服务(显示激活)
*/
Intent service = new Intent(this, StudentService.class);
//BIND_AUTO_CREATE绑定自动创建
bindService(service, conn, BIND_AUTO_CREATE);
}
private class StudentServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iStudent = (IStudent) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
iStudent = null;
}
}
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}
一个接口
package cn.wonder.studertno;
public interface IStudent {
public String queryStudent(int no);
}