我对绑定服务有疑问。我有父活动和几个片段,我绑定和解除绑定服务与活动,现在我可以访问片段中的服务吗?我需要在Fragments中使用ServiceConnection。
答案 0 :(得分:0)
是的,您可以通过以下方式访问片段内的父活动服务:
getActivity().getMyService()
答案 1 :(得分:0)
===========你的活动=================
callbackFragmentServiceConnection callbackfragment;
public interface callbackFragmentServiceConnection{
public void servicefun(MusicPlayService musicPlayService);
}
public void registerClientFragment(Fragment fragment){
this.callbackfragment = (callbackFragmentServiceConnection)fragment;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
mBound = true;
callbackfragment.servicefun(musicPlayService);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
=================在您的片段中=============
public class FragmentLibraryTrack extends Fragment implements
MainActivity.callbackFragmentServiceConnection {
MainActivity mainActivity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mainActivity= (MainActivity) context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainActivity.registerClientFragment(this);
}
@Override
public void servicefun(MusicPlayService musicPlayService) {
Log.e("reached sucessfully","yes");
}
}