Activity binding a Service throws NullPointerException

893 views Asked by At

In my Activity I have instance variables LocalBinder mBinder ;ServiceConnection mConnection; andboolean mBound;`

In onCreate I instantiate a ServiceConnection and set it to mConnection like this:

mConnection=new ServiceConnection()
{
   public void onServiceConnected(ComponentName class name,IBinder service){
     Log.d(TAG,"Service connected");
     mBinder=(LocalService.LocalBinder)service;
 }

And I set mBinder to null in onServiceDisconnected(ComponentName className)

The problem seems to be that the call to bind the a service using:

Intent intent=new Intent(MainActivity.this,LocalService.class);
   bindService(intent,mConnection,Context.BIND_AUTO_CREATE);

never occurs...thus ServiceConnection is never called...and when I use a public method in the LocalBinder class it throws an exception because binder is null.

I have a non-null ServiceConnection object and am using the right context.The Activity is launched on app start.The LocalBinder is as you might have guessed a static inner class of LocalService.

The Local Service looks like this:

 static  class LocalBinder
{
     public int getRandomNumber()
    {
         return (int)(Math.random()*100);
    }
 }

  public IBinder onBind(Intent intent)
  {
     LocalBinder binder=new LocalBinder();
      return binder;
     }

The service starts when I implement onStartCommand and startService(intent); but it won't bind...Service Connected will not display even though bindService returns true...thus the IBinder is not passed to the Activity causing a NullPointerException

1

There are 1 answers

0
John Riehl On

I don't think you're supposed to create a ServiceConnection()--rather, I think you implement the ServiceConnection interface in your Activity, then pass the Activity in bindService:

public class MyClientActivity extends Activity implements ServiceConnection {

    @Override
    public void onStart() {
        bindService(new Intent(MainActivity.this,LocalService.class), this, BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d(TAG,"Service connected");
        mBinder=(LocalService.LocalBinder)service;
    }

You'll also need to implement onServiceDisconnected(). Hope that helps.