用service来进行查询

来源:互联网 发布:雨佳会计软件 编辑:程序博客网 时间:2024/06/04 20:13

一、service

public class StudentService extends Service {private String[] students = {"天线ddb","痕","license"};private IBinder binder = new StudentBinder();@Overridepublic IBinder onBind(Intent intent) {return binder;}private String QueryStudentName(int studentNo){if(studentNo>0 && studentNo<=students.length)return students[studentNo-1];return null;}private final class StudentBinder extends Binder implements IStudentBinder{/* (non-Javadoc) * @see com.example.studentservice.IStudentBinder#QueryName(int) */@Overridepublic String QueryName(int studentNo){return QueryStudentName(studentNo);}}}

二、activity

public class MainActivity extends Activity {private ServiceConnection conn = new StudentServiceConnection();private IStudentBinder studentService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent service = new Intent(this,StudentService.class);bindService(service, conn, BIND_AUTO_CREATE);}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(conn);}public void query(View v){EditText studentNoText = (EditText)this.findViewById(R.id.studentNo);int studentNo = Integer.valueOf(studentNoText.getText().toString());String studentName = studentService.QueryName(studentNo);TextView studentNameText = (TextView) this.findViewById(R.id.studentName);studentNameText.setText(studentName);}
//如果没有注册服务,就调用不了onServiceConnectioned 方法private class StudentServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {studentService = (IStudentBinder)service;}@Overridepublic void onServiceDisconnected(ComponentName name) {studentService=null;}}}


0 0