Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

android - onServiceConnected never called after bindService method

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. I have chosen to use AIDL to make it possible. Everything seems works good except for bindService() method called in onCreate() of the activity. bindService(), in fact, throws a null pointer exception because onServiceConnected() is never called while onBind() method of the service is. Anyway bindService() returns true. The service is obviously active because it starts the activity. I know that calling an activity from a service could sound strange, but unfortunately this is the only way to have speech recognition in a service.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...