Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an Android Service know that its not bound to any Activities

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

like image 823
tunneling Avatar asked Jun 05 '10 14:06

tunneling


People also ask

What is bound services in Android?

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’.

How do I bind to a service in Android?

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.

What is the difference between bindservice() and onserviceconnected()?

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.

What does it mean to bind a service?

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).


1 Answers

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. **

like image 168
SharkAlley Avatar answered Oct 13 '22 00:10

SharkAlley