Junior — Middle
What methods are used to interact with Bound Service in Android?
sobes.tech AI
Answer from AI
Interaction with Bound Service in Android is carried out through the following methods:
-
Binding: The client (e.g., Activity) binds to the service via
bindService(). Upon successful binding, theonServiceConnected()method is called, where the client receives anIBinderobject to interact with the service. -
Calling service methods: Using the obtained
IBinder, the client can directly call the public methods of the service, allowing data exchange and service management. -
Unbinding: When the interaction ends, the client calls
unbindService()to disconnect.
Example of a simple Bound Service:
public class MyService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public int getRandomNumber() {
return new Random().nextInt(100);
}
}
// In Activity
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.LocalBinder binder = (MyService.LocalBinder) service;
myService = binder.getService();
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
bindService(intent, connection, Context.BIND_AUTO_CREATE);
Thus, interaction occurs through the IBinder interface and the bindService/unbindService methods.