I am creating a small app using Mosby.
The app has a service which I want to bind to. I guess the correct place to do this is in the presenter. But I can't really figure out how to do it.
What I want to archive is when the service is bound I want to call a method on it and push that value to the view, so that the state right now is correct.
When the service sends updates on the event bus I want to push that to the view as well.
I have found some example on the later part, but nothing about how to bind/unbind the service in the presenter.
My stab on it was to create something like this in the activity:
@NonNull
@Override
public MyPresenter createPresenter() {
return new MyPresenter(new MyService.ServiceHandler() {
@Override
public void start(ServiceConnection connection) {
Intent intent = new Intent(MyActivity.this, MyService.class);
startService(intent);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
public void stop(ServiceConnection connection) {
unbindService(connection);
}
});
And then in the presenter do something like this:
private ServiceConnection connection;
private boolean bound;
private MyService service;
public MyPresenter(MyService.ServiceHandler serviceHandler) {
super(new MyViewState.NotInitialiezedYet());
this.serviceHandler = serviceHandler;
connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MyService.LocalBinder binder = (MyService.LocalBinder) service;
service = binder.getService();
bool isInitialized = service.isInitialized();
// how do i push isInitialized to view?
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
}
@Override
public void attachView(@NonNull SplashView view) {
super.attachView(view);
serviceHandler.start(connection);
bound = true;
}
@Override
public void detachView(boolean retainInstance) {
super.detachView(retainInstance);
if(bound) {
serviceHandler.stop(connection);
bound = false;
}
}
@Override
protected void bindIntents() {
//Not sure what this would look like?
}
public void onEventInitialized(InitializedEvent event) {
//how do I push this to the view?
}
Am I on the correct path? What would be the correct way of doing this? How would I send the value from the service to the view in onServiceConnected and when I get events on the event bus in onEventInitialized?