從埃裏克森的回答:
我被引用計數在應用程序綁定服務 解決了這個問題。每個Activity都必須在其onCreate()方法中調用 acquireBinding(),並在onDestroy()中調用releaseBinding() 。如果參考計數器達到零,則發佈綁定爲 。
我同意,但你不應該在onDestroy中做 - 它通常不會被調用。
相反,我建議如下(根據您的代碼示例)...
// 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
protected void onPause() {
super.onPause();
// Pre-HC, activity is killable after this.
if ((11 > Build.VERSION.SDK_INT) && (isFinishing()))
onFinishing();
}
@Override
protected void onStop() {
super.onStop();
if ((10 < Build.VERSION.SDK_INT) && (isFinishing()))
onFinishing();
}
protected void onFinishing() {
// Do all activity clean-up here.
this.app.releaseBinding();
}
}
,但我使用isFinishing的()僅僅是一個想法 - 我不能肯定它是可靠的。也許onPause/onStop被isFinishing()調用爲false,但是然後活動被殺死 - 並且您的releaseBinding()永遠不會被調用。
如果你擺脫了isFinishing檢查,我認爲你需要將onCreate中的acquireBinding()調用移動到onStart/onResume(取決於sdk版本),以確保你的ref count不會混亂。
誰知道釋放你的應用程序的服務將非常複雜!
來源
2012-03-31 21:42:16
Tom
您的服務如何在屏幕旋轉中生存? – 2014-01-07 23:40:45
你是什麼意思? Android中的服務沒有UI,因此它可以繼續運行。在這種情況下,Service先前使用'context.startService()'啓動,並被標記爲sticky,以便它運行直到它被手動停止或停止。 – 2014-01-08 09:28:29
我明白了。我在想,釋放綁定會停止服務,但不是在這種混合服務的情況下。釋放綁定以避免泄漏的服務連接。 – 2014-01-08 20:44:30