onServiceConnected never called after bindService method

后端 未结 12 654
醉话见心
醉话见心 2020-11-30 05:48

I have a particular situation: a service started by a broadcast receiver starts an activity. I want to make it possible for this activity to communicate back to the service.

12条回答
  •  -上瘾入骨i
    2020-11-30 06:21

    After hours and hours of trying to figure this out, the issue is that the examples that show the creation of the service, don't include the onBind method or they have the following sample code or it generates this for you:

    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    

    This causes the onServiceConnected method to fail or never actually get executed. The fix is VERY simple, which is the following:

    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    

    Where you could create a simple binder such as the following to return:

    private final IBinder mBinder = new LocalBinder();
    public class LocalBinder extends Binder {
        public ConferenceService getService() {
        return ConferenceService.this;
      }
    }
    

提交回复
热议问题