Service使用——不同应用程序间的绑定与信息传递

本文详细介绍了如何在同一应用程序内绑定Service以及不同应用程序间如何通过Service进行绑定和信息传递。涉及步骤包括自定义Service、Binder,重写onBind()方法,实现ServiceConnection,使用Messenger进行跨进程通信等。
摘要由CSDN通过智能技术生成

Service是android四大组件之一,通常很多后台的工作会交给Service,如音乐的播放什么的,这里不介绍Service的生命周期什么的,主要介绍如何绑定Service并进行信息传递。

一、同个App绑定Service

步骤1:自定义一个继承Service的类,如叫MyService;

步骤2:在MyService类中自定义一个继承Binder的内部类,如叫MyIBinder;

步骤3:重写MyService的onBind(Intent intent)方法,返回一个MyIBinder的实例对象,参数intent为绑定MyService的Activity或ContentProvider传过来的(信息可通过intent传递过来);

步骤4:在MyIBinder类中实现一些方法,将要从Service传递出去的信息通过这些方法返回。

(以上是在Service部分做的操作,接下去的步骤是在需要绑定Service的方法做的操作)

步骤5:实例化一个ServiceConnection的对象,并重写onServiceConnected(ComponentName componentName, IBinder iBinder)和onServiceDisconnected(ComponentName componentName)方法;

onServiceConnected:在service绑定时执行,参数componentName是组件的名称,参数iBinder是Service的onBind方法返回的IBinder 对象(在步骤3中我们返回的是MyIBinder对象,所以获得的也是MyIBinder对象,我们就可以通过调用MyBinder对应的方法来获得我们需要的数据)。

onServiceDisconnected:在断开绑定,或者service被杀死时执行。

步骤6:实例化Intent对象,绑定Service,需要传递给Service的信息通过Intent传过去。


Service的代码如下:

public class MySevice extends Service {
	
	private MyIBinder iBinder;
	
	public MySevice(){
		iBinder = new MyIBinder();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return iBinder;
	}
	
	public class MyIBinder extends Binder{
		public String getName(){
			return "From Service Info";
		}
	}
}

调用Service的代码如下:

public class MainActivity extends Activity {
	
	private TextView mTextView;<span style="white-space:pre">		</span>// 显示Service传递过来信息的控件
	private Button mStartButton;<span style="white-space:pre">		</span>// 绑定Service的按钮
	
	@Override
	protected void onCreate(Bundle sav
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值