Junior — Middle
What mechanisms exist for data exchange between Activity and Service in Android?
sobes.tech AI
Answer from AI
In Android, several main mechanisms are used for data exchange between Activity and Service:
-
Intent with extras
- Activity can start a Service via
startService(Intent), passing data through extras. - Service can send data back via
BroadcastReceiverorPendingIntent.
- Activity can start a Service via
-
Bound Service
- Activity binds to the service using
bindService(), obtains an interface (Binder), and directly calls service methods for data exchange.
- Activity binds to the service using
-
BroadcastReceiver
- Service sends broadcast messages, which are received by Activity.
-
Messenger or AIDL
- For inter-process communication (IPC),
MessengerorAIDLare used.
- For inter-process communication (IPC),
-
Using shared data storage components
- SharedPreferences, databases, files — the service and activity can read and write data there.
Example of using 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 MyService myService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.LocalBinder binder = (MyService.LocalBinder) service;
myService = binder.getService();
int number = myService.getRandomNumber();
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
// Binding to the service
bindService(new Intent(this, MyService.class), connection, Context.BIND_AUTO_CREATE);
Thus, the choice of mechanism depends on the task: for simple one-way communication — Intent, for two-way and more complex — Bound Service.