Android开发入门之建立能与访问者进行相互通信的本地服务

StudentService

package cn.leigo.studentquery;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class StudentService extends Service {
	private StudentBinder binder = new StudentBinder();
	private String[] names = { "张三", "李四", "王五" };

	public String queryStudentByNo(int no) {
		if (no > 0 && no < 4) {
			return names[no - 1];
		}
		return null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	private class StudentBinder extends Binder implements IStudent {

		@Override
		public String queryStudent(int no) {
			return queryStudentByNo(no);
		}

	}

}

<service android:name="cn.leigo.studentquery.StudentService" />

IStudent

package cn.leigo.studentquery;

public interface IStudent {

	public String queryStudent(int no);

}

MainActivity

package cn.leigo.studentquery;

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 implements OnClickListener {
	private EditText mStudentNoEditText;
	private Button mQueryButton;
	private TextView mResultTextView;
	private StudentServiceConnection conn = new StudentServiceConnection();
	private IStudent iStudent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mStudentNoEditText = (EditText) findViewById(R.id.et_student_no);
		mQueryButton = (Button) findViewById(R.id.btn_query);
		mResultTextView = (TextView) findViewById(R.id.tv_result);
		mQueryButton.setOnClickListener(this);

		Intent service = new Intent(this, StudentService.class);
		bindService(service, conn, BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(conn);
	}

	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
	public void onClick(View v) {
		String no = mStudentNoEditText.getText().toString();
		String name = iStudent.queryStudent(Integer.parseInt(no));
		mResultTextView.setText(name);
	}

}


你可能感兴趣的:(android,service)