开发者

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


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


I cannot comment on SharkAlley's answer so I replay here.

Unfortunately onBind() is not called each time a client connects. See for example Mrs Hackborne's answer here: https://groups.google.com/d/msg/android-developers/2IegSgtGxyE/iXP3lBCH5SsJ

A possible solution is to return true from onUnbind() and set the flag to true both on onBind() and onRebind() (and false on onUnbind()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜