OnServiceConnected does not receive a call
I have already referenced the following questions but could not find an answer:
- Can not get the service object (onServiceConnected never invoked) ,
- onServiceConnected is not called getting a null pointer exception and
- onServiceConnected is never called after bindService method
Here is my code:
@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
}
}
and my service class does not contain anything, just this, I showed it below
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
}
}
But in lolcat I only get " bound
" a message from the onBind () function, but I don't print " Pod: Service Connected
", so the service has started successfully. and in lolcat i get NullPointerException
and is also mentioned in the manifest file too.
+3
source to share
1 answer
I rewrote the service class so that onBind () returns IBinder as follwos.
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
}
}
and now it works.
+1
source to share