Fragmet+Tabhost+重复绑定service

来源:互联网 发布:lindsey stirling 知乎 编辑:程序博客网 时间:2024/06/02 06:36

有时为了减少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() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubbound = false;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubbound = true;}};
这样就可以重复绑定同一个service了。


2 0
原创粉丝点击