Middle
Miks kasutatakse teenustes meetodit onBind?
sobes.tech AI
Vastus AI-lt
The onBind method is used to bind a component (e.g., an Activity) to a service. It returns an implementation of the IBinder interface, through which interacting components can call the service's methods.
// Example implementation of onBind in a Service
public class MyBoundService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyBoundService getService() {
// Returns an instance of the service
return MyBoundService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
// Returns the Binder instance
return binder;
}
// Methods accessible via Binder
public int doSomething() {
// ... perform some operation ...
return 42;
}
}
When using onBind:
- The service is not destroyed by the system as long as clients are bound to it.
- Multiple clients can connect to the service simultaneously.
- The returned
IBinderprovides a way for clients to directly invoke the service's methods.
Bound services are used to implement long-running background tasks that need to interact with UI components (e.g., music playback, file uploads with progress).