Android中和service进行本地通讯

本文通过一个查询学号的简单示例,详细介绍了在Android应用中如何与Service进行本地通讯,包括交互流程和服务代码实现。
摘要由CSDN通过智能技术生成

查询学号的简单例子

交互图


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

久梦歌行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值