在应用程序完全绑定/解除绑定到服务绑定、应用程序

由网友(超级红地毯)分享简介:我有一个Android应用程序绑定到一个持久化服务(一旦开始使用 startService())。I have an Android application that is binding to a persistent service (once started with startService()).该服务是...

我有一个Android应用程序绑定到一个持久化服务(一旦开始使用 startService())。

I have an Android application that is binding to a persistent service (once started with startService()).

该服务是应用程序的一个组成部分,因此被用在几乎每一个活动。因此,我希望绑定到该服务只有一次(而不是绑定/解除绑定在每一个活动),并保持绑定我的应用程序的生命周期中。

The service is an integral part of the application and thus is used in almost every Activity. Hence I want to bind to the service just once (instead of binding/unbinding in every Activity) and keep the binding during the lifetime of my application.

我从应用程序延伸和绑定到Application#onCreate().不过,我现在有这个问题,我不知道,因为Application#onTerminate()永远不会被调用,看到的JavaDoc:

I've extended from Application and bind to the service in Application#onCreate(). However I now have the problem that I don't know when my application exists since Application#onTerminate() is never called, see JavaDoc:

这方法是在模拟过程中的环境中使用。它永远不会   被称为生产Android设备,在处理被删除的   通过简单地杀死他们。没有用户code(包括该回调)是   执行这样做的时候。

This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

那么,如何干净地绑定在应用程序服务取消绑定?

So how do I cleanly unbind from a service bound in Application?

推荐答案

我通过计算引用了服务于应用程序结合解决了这个问题。每个活动还打电话叫 acquireBinding()在他们的onCreate()方法和呼叫 releaseBinding()的onDestroy()。如果引用计数器达到零的结合被解除。

I solved this problem by counting the references to the service binding in the Application. Every Activity has to call acquireBinding() in their onCreate() methods and call releaseBinding() in onDestroy(). If the reference counter reaches zero the binding is released.

下面是一个例子:

class MyApp extends Application {
    private final AtomicInteger refCount = new AtomicInteger();
    private Binding binding;

    @Override
    public void onCreate() {
        // create service binding here
    }

    public Binding acquireBinding() {
        refCount.incrementAndGet();
        return binding;
    }

    public void releaseBinding() {
        if (refCount.get() == 0 || refCount.decrementAndGet() == 0) {
            // release binding
        }
    }
}

// Base Activity for all other Activities
abstract class MyBaseActivity extend Activity {
    protected MyApp app;
    protected Binding binding;

    @Override
    public void onCreate(Bundle savedBundleState) {
        super.onCreate(savedBundleState);
        this.app = (MyApp) getApplication();
        this.binding = this.app.acquireBinding();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.app.releaseBinding();
    }
}
阅读全文

相关推荐

最新文章