0

Code:

@Override
public void onResume() {
    super.onResume();

    Intent intent = new Intent(getActivity(), UserAPIService.class);
    getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    mService.fetchUserInfo();
}

private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        UserAPIService.LocalBinder binder = (UserAPIService.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};

The user info is attempted to be fetched, but the service is null because it hasn't been bound yet. What is the best way to go about this? I could make the API call in the onServiceConnected method, but there has to be a better way.

Nick
  • 925
  • 1
  • 8
  • 13

1 Answers1

0

You can call the

mService.fetchUserInfo();

inside the method

onServiceConnected(ComponentName className,IBinder service)

You cannot get the service instance unless your service is bound and it may require some time . onStart() is better place to bind a service.

Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
  • What if I create a singleton in the application class of the api service? – Nick Jan 29 '15 at 18:38
  • @Nick: If the service depends on the binding, then that would be a good idea, to prevent it being destroyed when the `Activity` is restarted due to configuration changes. You will have to manage the binding lifecycle yourself appropriately in that case though. – corsair992 Jan 29 '15 at 20:48