Fragmet+Tabhost+重复绑定service

有时为了减少activity的使用,会使用fragment来填充页面,我在使用fragment和tabhost时,绑定service时不能正常绑定,发现在与一般的绑定写法不同,解除绑定也有略微的不同,下面分享给大家。

在进行填充的那个fragmentactivity里,先写:

private Intent intent;
再在onCreate()方法里写:
intent = getIntent();
如果是在一开始就进行填充页面则在onCreate()方法里写:
intent.setClass(你写的fragmentactivity.this, 你写的服务类.class);

	this.getApplicationContext().bindService(intent, connection,Context.BIND_AUTO_CREATE);
这样就可以绑定上,因为使用到了tabhost所以写法才会略有不同(个人观点)。如果填充的每一个界面都需要绑定一次service时,则在绑定service前先进行判断,判断是否绑定了服务,如果没绑定则绑定,如果已经绑定了服务则先解除绑定再重新绑定服务。

判断时先写一个全局变量bound 初始false,在再你写的绑定服务前写一个判断:

if (bound) {
			this.getApplicationContext().unbindService(connection);// 解除绑定
		}

绑定时还需写一个:

ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

			bound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub

			bound = true;
			
		}
	};
这样就可以重复绑定同一个service了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值