How to catch bindService failure

529 Views Asked by At

I have some foregraund IntentService which could be ran or stopped. I need to reflect its progress(current state which is quite complex) on the Activity if it is visible.

I did not find the reliable and good way to find out whether my IntentService is running and ready to be bound to my Activity.

If I do bindService it always returns true. In case the IntentService is not ran the onServiceConnected(as well as any other callbacks) is never called and my activity remains in the preparation state for always.

The only working solution I found was the static variable in my IntentService class which indicates the service is running. But I believe that is bad practice to use such approach and many people warn it could not work or be unpredictable for some cases.

QUESTION: How do developers of Android expect to handle the failure of bindService call?

And particular case: what to do in case if we are trying to bind to the service which is not running now or in some intermediate state(e.g. shutting down etc).

1

There are 1 best solutions below

4
Mahavir Jain On
    private UploadService.Binder mServiceBinder;

    @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            createService();
        }

    private void createService() {
            if (mServiceBinder == null)
                bindService(new Intent(this, UploadService.class),
                        mConnection,
                        Context.BIND_AUTO_CREATE);
        }

private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mServiceBinder = ((UploadService.Binder) service);
            ((UploadService.Binder) service).getService().setCallback(DashFragment.getInstance());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceBinder = null;
        }
    };
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mServiceBinder != null) {
                unbindService(mConnection);
                mServiceBinder = null;
            }
        }

If the mServiceBinder is not null means your service is successfully bounded to the activity else you have to call create service method.