I have an Android Service that I would like to keep running even after the last Activity has been popped off the stack, or the User has chosen to do something else.
Essentially the Service is listening for changes on a remote server, and I would like to generate a Notification if and only if an Activity from the app isn't running(or visible). In other words, I don't want the Notifications to occur while the User is directly interacting with the app.
In the case where the User is directly interacting with the app, the Service will notify the Activity and update appropriate UI elements based on the changes. I plan to implement this through the Observer pattern.
How can the Service know if none of apps Activities are bound to it?
Thanks, J
Bound And Foreground Services in Android, A step by step guide. In Android applications sometimes we often need that Activities/Other apps can communicate with each other. For this medium, we can use ‘Bound services’.
Application components (clients) can bind to a service by calling bindService(). The Android system then calls the service's onBind() method, which returns an IBinder for interacting with the service. The binding is asynchronous, and bindService() returns immediately without returning the IBinder to the client.
The bindService () method returns immediately without a value, but when the Android system creates the connection between the client and service, it calls onServiceConnected () on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the service. Multiple clients can connect to the service at once.
A service is bound when an application component binds to it by calling bindService (). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC).
You need to use a boolean with the onBind, onUnbind and onRebind methods:
public boolean bound;
@Override
public Binder onBind(Intent intent){
bound = true;
return myBinder; //declare and init your binder elsewhere
}
@Override
public boolean onUnbind(Intent intent) {
bound = false;
return true; // ensures onRebind is called
}
@Override
public void onRebind(Intent intent) {
bound = true;
}
onUnbind is only called when all clients have disconnected. Thus bound will stay true until all clients have disconnected.
** NOTE: Edited based on feedback from Gil. **
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With