Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active September 6, 2019 05:34
Show Gist options
  • Save mitchtabian/4166de0d825288f7d3bf5bd2c5728909 to your computer and use it in GitHub Desktop.
Save mitchtabian/4166de0d825288f7d3bf5bd2c5728909 to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
MyService mService;
Boolean mIsBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
startService();
}
@Override
protected void onStop() {
super.onStop();
if(mIsBound){
unbindService(serviceConnection);
mIsBound = false;
}
}
private void startService(){
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
bindService();
}
private void bindService(){
Intent serviceBindIntent = new Intent(this, MyService.class);
bindService(serviceBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder iBinder) {
Log.d(TAG, "ServiceConnection: connected to service.");
// We've bound to MyService, cast the IBinder and get MyBinder instance
MyService.MyBinder binder = (MyService.MyBinder) iBinder;
mService = binder.getService();
mIsBound = true;
getRandomNumberFromService(); // return a random number from the service
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d(TAG, "ServiceConnection: disconnected from service.");
mIsBound = false;
}
};
private void getRandomNumberFromService(){
Log.d(TAG, "getRandomNumberFromService: Random number from service: " + mService.getRandomNumber());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment