我有一个Activity类,在它的onResume部分,我使用了下面的代码-
@Override
protected void onResume() {
super.onResume();
bindService(new Intent(MainActivity.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
}在onPause,我使用了下面的代码-
@Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}正如您所理解的,我正在绑定和解除绑定到一个服务。
现在的问题是,我想使用片段而不是Activity。
为了做到这一点,我把onPuse代码改成了这样-
@Override
protected void onPause()
{
getActivity().unbindService(mConnection);
super.onPause();
}看起来挺好的。
但我在onResume中遇到的问题是绑定部分,我已经尝试了下一个代码-
@Override
protected void onResume() {
super.onResume();
bindService(new Intent(getActivity(), IMService.class), mConnection , Context.BIND_AUTO_CREATE);
}但是Eclipse给了我一个错误,说-
The method bindService(Intent, ServiceConnection, int) is undefined for the type MainFragment服务在清单中如下所示-
<service android:name="com.example.test.services.IMService" >
</service>那么为什么我不能将服务绑定到片段中呢?也许我需要在getActivity代码中添加一些东西?
感谢任何形式的帮助
感谢@Raghunandan的帮助-这就是解决方案-
getActivity().bindService(new Intent(getActivity(), IMService.class), mConnection , Context.BIND_AUTO_CREATE);发布于 2014-04-24 19:57:19
使用
getActivity().bindService(params)它需要一个Context
发布于 2021-02-12 01:05:17
开始:
Intent intent = new Intent(getActivity(), OdometrService.class);
getActivity().bindService(intent, connection, Context.BIND_AUTO_CREATE);停止:
getActivity().unbindService(connection);https://stackoverflow.com/questions/23268010
复制相似问题