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);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值