Created
March 20, 2017 12:51
-
-
Save Nimrodda/865ceabdd19514cfb7ef92c57a0c922e to your computer and use it in GitHub Desktop.
Android Bound Service and MVP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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