0

I am trying to bind a service in the MainActivity, the bind service is bound by a intent that is created in the method updateTheNotification() defined inside MainActivity as given below :

public void updateTheNotification()
    {

        Intent intentz = new Intent(context.getApplicationContext(), NotificationService.class);
        context.getApplicationContext().bindService(intentz, mConnection, Context.BIND_ABOVE_CLIENT);
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            mService.changeTheUI(true);
            Toast.makeText(this, "Service triggered", Toast.LENGTH_LONG).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            NotificationService.LocalBinder binder = (NotificationService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

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

updateTheNotification() is called by the Broadcast receivers onReceive method which is attached to a button on the notification.

IteratioN7T
  • 363
  • 8
  • 21

1 Answers1

0

The method bindService() is asynchronous. That means that the method returns immediately, even though the Service is not yet bound.

When the Service binding is complete, the onServiceConnected() method of the ServiceConnection is called. Since this method is called on the main (UI) thread, it cannot be called while code is executing in any other method that is also called on the main (UI) thread (for example, onReceive().

You need to split your processing into 2 parts:

  1. bind to Service
  2. after Service is connected, continue processing
David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Yes that is why i dropped the idea of binder because i wanted to update the UI too. So what i did was i made the service independent of MainActivity, in my case i am handling mediaplayer in a seperate service, and making a call using the intent filter actions. – IteratioN7T Jan 26 '17 at 16:50