Skip to content

Instantly share code, notes, and snippets.

@Nimrodda
Created March 20, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nimrodda/865ceabdd19514cfb7ef92c57a0c922e to your computer and use it in GitHub Desktop.
Save Nimrodda/865ceabdd19514cfb7ef92c57a0c922e to your computer and use it in GitHub Desktop.
Android Bound Service and MVP
public class ChatService extends Service {
public class LocalBinder extends Binder {
public MessagingService getService() {
return ChatService.this.mMessagingService;
}
}
private final IBinder mBinder = new LocalBinder();
@Inject MessagingService mMessagingService;
@Override
public void onCreate() {
super.onCreate();
DaggerMessagingServiceComponent.builder()
.messagingServiceModule(new MessagingServiceModule())
.build()
.inject(this);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return false;
}
}
public class MainActivity extends AppCompatActivity implements ServiceConnection {
private boolean mBound;
@Inject MainPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerMainComponent.builder()
.mainModule(new MainModule())
.build()
.inject(this);
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(context, ChatService.class);
mBound = bindService(intent, this, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mPresenter.attach(((ChatService.LocalBinder)service).getService());
}
@Override
public void onServiceDisconnected(ComponentName name) {
mPresenter.detach();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment