tags:

views:

71

answers:

1

This is my code:

public class MainActivity extends Activity {
    private ComponentName mService;
    private Servicio serviceBinder;

    private ServiceConnection mConnection = new ServiceConnection() {
           public void onServiceConnected(ComponentName className, IBinder service) {
             serviceBinder = ((Servicio.MyBinder)service).getService();
           }

           public void onServiceDisconnected(ComponentName className) {
             serviceBinder = null;
           }
        };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent bindIntent = new Intent(this, Servicio.class);
        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        serviceBinder.somethingThatTakesTooMuch();
        super.onStart();
    }



public class Servicio extends Service {
    private final IBinder binder = new MyBinder();

    @Override
            public IBinder onBind(Intent intent) {
    return binder;
    }

    public int somethingThatTakesTooMuch() {
        return 1;
    }

    public class MyBinder extends Binder {
          Servicio getService() {
            return Servicio.this;
          }
    }

When I run it, It get a NullPointerException in this line:

serviceBinder.somethingThatTakesTooMuch();
+3  A: 

Your onStart is being called before the connection to the service is complete. It's not instant.

You can only guarantee that the service is connected AFTER your onServiceConnected is called. Only then can you call methods on serviceBinder.

Try calling serviceBinder.somethingThatTakesTooMuch() on the line after serviceBinder = ((Servicio.MyBinder)service).getService();

synic
synic: Oh, how do you think I should handle that I can't show my Activity until I get the connection?
Macarse
Good question. I don't know. You could probably minimize the time it takes by creating it beforehand (possibly in another Activity)
synic
The connection should be very quick, but it is not immediate nor blocking. Hence, I would not worry about the time -- just write your code that needs the service such that it is triggered by `onServiceConnected()`.
CommonsWare