0

My question is exactly as it says on the title. Why is it that Android bound services always load after a whole fragment lifecycle is complete? Bound services are meant to be loaded on the activity containing the fragment, so why is it that the service is only available after the fragment is created? Sometimes I want to use the service to populate things in the fragment and needed to recur to "hacks" to get to use the service.

I load the service connections in the onCreate() method in the activity and start the service in OnStart() as described by the documentation https://developer.android.com/guide/components/bound-services but then I have to create a "loading" method in the fragment to load stuff once the service finished loading.

    private void loadServiceConnections()
    {
        metronomeConnection = new ServiceConnection()
        {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service)
            {
                MetronomeService.LocalBinder localBinder = (MetronomeService.LocalBinder) service;
                metronomeService = localBinder.getService();
                metronomeService.setLinkManager(notificationsMetronomeLinkManager);
                metronomeService.setListener(myFragment);
                metronomeFragment.onServiceLoading(); //this is the method that executes inside the fragment once the service is available.

                metronomeServiceIsBound = true;


                if (loaded && metronomeService.isMetronomePlaying())
                    metronomeRunning = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName name)
            {
                metronomeServiceIsBound = false;
            }
        };
}
JoanaBrew
  • 11
  • 4
  • "bound services always load after a whole fragment lifecycle is complete?" - The callbacks in the `ServiceConnection` happen independent of an `Activity` or `Fragment` lifecycle hooks. – Mark Dec 24 '20 at 14:47
  • `onServiceConnected` callback is posted on main looper so unfortunately it does not block and won't happen until fragments lifecycle methods that are already enqueued on main looper finish executing. – Pawel Dec 24 '20 at 14:53
  • Thank you Pawel! So is there a better way to call a method inside a fragment that depends on the service? – JoanaBrew Dec 25 '20 at 15:03

0 Answers0