bindService的注意事项
private ServiceConnection conn = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
binder = (MyBinder) service;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = new PlayIndex(binder.cur,binder.list);
ft.replace(R.id.play, fragment);
ft.commit();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
Intent intent = new Intent(Play.this, PlayService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
bindService的调用是异步的,也就是说到service的链接不是在bindService被调用后就马上完成的。不了解这一点会导致一些问题,例如:虽然在bindService.onServiceConnected中有对binder的赋值,但如果以为在onCreate中的bindService之后onServiceConnected就已经被调用了,就会出现问题,因为其实这时binder仍然是null,到service的链接会在之后的某个时间点被建立,建立链接后系统会调用onServiceConnected这个函数,所以可以在这个函数中放置一些代码来提醒当前activity到service的链接已经建立完毕。但具体最晚到什么时候还不知道,猜测应该是onCreate执行完毕后吧。
更多相关文章
- android 联系人搜索
- Android(安卓)Uri.getQueryParameter使用注意
- 调用getChildFragmentManager时出现的Bug
- Android(安卓)直接通过JNI访问驱动
- Android(安卓)SQLite数据库增删改查
- android支付宝 KeyFactory PrivateKey
- android个推消息推送,asp.net调用接口
- Android(安卓)API Level 与 Platform Version之间的关系
- DrawLayout几个注意点