1

There are numerous questions with the same title but they didn't help. So I am asking.

I Have a service which is started successfully in my first activity. when switching to the second activity, I need to bind with the service. But the onServiceConnected is never called.

(Note: I work on an emulator, and used this example to implement the binding)

Activity:

public class GameActivity extends NativeActivity implements GroupInfoListener 
{   
    public SimmobBroker broker;// <- this is my service
    ServiceConnection cnn= new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name,
                IBinder service) {
            Log.i(TAG,"onServiceConnected");
            SimmobBrokerBinder binder = (SimmobBrokerBinder) service;
            broker = binder.getService();
            Log.i(TAG,"onServiceConnected...now initializing the activity");
            InitializeActivity();           
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };  

        @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, SimmobBroker.class);
        getApplicationContext().bindService(intent, cnn, getApplicationContext().BIND_AUTO_CREATE);
//      InitializeActivity();
    }
};

Service:

public class SimmobBroker   extends Service {
    @Override
    public void onCreate() {
        Log.i(TAG, "SimmobBroker Created");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "SimmobBroker onStartCommand");
        myHandler.post(simmobConnect);
        return START_STICKY;
    }

    @SuppressLint("HandlerLeak")
    public final Handler myHandler = new Handler() {/*...*/}

    private final IBinder myBinder = new SimmobBrokerBinder();

    public class SimmobBrokerBinder extends Binder {
        public SimmobBroker getService() {
            return SimmobBroker.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    } 
};

Thank you for your kind help.

rahman
  • 4,820
  • 16
  • 52
  • 86

1 Answers1

0

Try to call bindService directly, not from application context.

bindService(intent, cnn, Context.BIND_AUTO_CREATE)
mauron85
  • 1,364
  • 1
  • 14
  • 28