Skip to content

Instantly share code, notes, and snippets.

@itstartstosnow
Last active February 17, 2022 06:59
Show Gist options
  • Save itstartstosnow/5461e8d674630a95fb1ae304b2f8a4cf to your computer and use it in GitHub Desktop.
Save itstartstosnow/5461e8d674630a95fb1ae304b2f8a4cf to your computer and use it in GitHub Desktop.
Android basic bind a service
public class MainActivity extends AppCompatActivity {
MyService.ServiceBinder mBinderService;
ServiceConnection mServConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinderService = (MyService.ServiceBinder) service;
// later call the binder to do something
mBinderService.someInterface(0);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, mServConn, BIND_AUTO_CREATE);
}
}
public class MyService extends Service {
public ServiceBinder mBinder = new ServiceBinder();
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class ServiceBinder extends Binder {
public void someInterface(int i) {
// do something, called by client
}
public MyService getService() {
// can also return this service so that client can all its any public method
return MyService.this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment