我有一个绑定到持久服务的
Android应用程序(一旦从startService()开始).
该服务是应用程序的组成部分,因此几乎在每个Activity中都使用.因此,我想要绑定到服务一次(而不是绑定/解除绑定在每个活动),并保持绑定在我的应用程序的生命周期.
我已经从Application扩展,并在Application#onCreate()绑定到服务.但是我现在有一个问题,我不知道我的应用程序是否存在,因为Application#onTerminate()从未被调用,请参阅JavaDoc:
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.
那么如何从应用程序中绑定的服务彻底解除绑定?
解决方法
我通过计算应用程序中对服务绑定的引用来解决这个问题.每个Activity必须在onCreate()方法中调用acquireBinding(),并调用onDestroy()中的releaseBinding().如果引用计数器达到零,则释放绑定.
以下是一个例子:
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(); } }