建立能和访问者相互通信的本地服务

当服务和访问者在一个进程时候,如果需要通信,普通的启动方式无法通信,故采用bindService()服务,返回一个IBinder对象,共安卓客户端调用服务中的方法

关键:接口(isStudent)把两个类连在了一起



应用,访问者

public class MainActivity extends Activity {
    private EditText studentno;
    private ServiceConnection conn = new StudentServiceConnection();
    private IStundent iStundent;
    private TextView resultView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        resultView = (TextView) this.findViewById(R.id.resultView);
        studentno = (EditText) this.findViewById(R.id.studentno);
        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new ButtonClickListener());
        Intent service = new Intent(this, StudentService.class);
        bindService(service, conn, BIND_AUTO_CREATE);             //绑定服务,中间参数用于数据交换
    }
    
    private class StudentServiceConnection implements ServiceConnection{
		public void onServiceConnected(ComponentName name, IBinder service) {//连接服务后返回一个IBinder对象
			iStundent = (IStundent)service;
		}
		public void onServiceDisconnected(ComponentName name) {
			iStundent = null;
		}
    }
    
    @Override
	protected void onDestroy() {   进程摧毁时解除绑定,进而停止服务
		unbindService(conn);
		super.onDestroy();
	}


	private final class ButtonClickListener implements View.OnClickListener{
		public void onClick(View v) {
			String no = studentno.getText().toString();
			String name = iStundent.queryStudent(Integer.valueOf(no));
			resultView.setText(name);
		}
    }
}
定义一个接口,用于IBinder对象调用service的方法
public interface IStundent {
	public String queryStudent(int no);
}
开启的服务
public class StudentService extends Service{
	private String[] names = {"张飞","李小龙","赵薇"};
	private IBinder binder = new StundentBinder();
	
	public String query(int no){
		if(no>0 && no<4){
			return names[no - 1];
		}
		return null;
	}
	
	@Override
	public IBinder onBind(Intent intent) { 用于向<span style="font-family: Arial, Helvetica, sans-serif;">onServiceConnected()方法返回IBinder对象</span>

		return binder;
	}
	
	private class StundentBinder extends Binder implements IStundent{
		public String queryStudent(int no) {
			return query(no);
		}	}
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值