我已经提到了以下问题,但找不到答案:
-
无法获取服务对象(onServiceConnected 从未调用),
-
onServiceConnected 没有被调用,出现空指针异常, and
- onServiceConnected 在bindService 方法之后从未调用
这是我的代码:
@Override
public void onStart() {
super.onStart();
Context context = getApplicationContext();
Intent intent = new Intent(context, PodService.class);
context.bindService(intent, mPodServiceConn, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mPodServiceConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.e(TAG, "Pod: Service Connected");
mPodService = IPodService.Stub.asInterface(service); //here i am getting NullPointerException
}
}
我的服务类什么也没有包含,只有这么多,我已经在下面展示了
public class PodService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d("bound", "bound");
return null;
}
static class PodSeviceStub extends IPodService.Stub {
//here i implemented unimplemented methods
}
}
但在 lolcat 中我只得到“bound
“来自 onBind() 函数的消息,但不打印”Pod: Service Connected
”,表示服务启动成功。
在 lolcat 我得到NullPointerException
并且在清单文件中也提到了。
我重写了服务类,以便 onBind() 返回 IBinder,如下所示。
public class PodService extends Service {
@Override
public IBinder onBind(Intent intent) {
Log.d("bound", "bound");
return mBinder; // returns IBinder object
}
private final IBinder mBinder = new PodSeviceStub(this);
static class PodSeviceStub extends IPodService.Stub {
WeakReference<PodService> mService;
public PodSeviceStub(PodService service) {// added a constructor for Stub here
mService = new WeakReference<PodService>(service);
}
//here i implemented unimplemented methods
}
}
现在可以了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)