2010-09-10 107 views
1

我使用bindService方法啓動服務。使用bindService保持android服務活着

但是,當我點擊在Android模擬器上的後退按鈕我的服務被銷燬。

如何在整個應用程序中保持服務(我必須使用bindService來與活動進行通信)?

感謝

更新 這是錯誤日誌

09-10 18:28:18.352: ERROR/ActivityThread(905): Activity com.flax.trainer.RunOnly has leaked ServiceConnection [email protected] that was originally bound here 
09-10 18:28:18.352: ERROR/ActivityThread(905): android.app.ServiceConnectionLeaked: Activity com.flax.trainer.RunOnly has leaked ServiceConnection [email protected] that was originally bound here 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.app.ActivityThread$PackageInfo$ServiceDispatcher.<init>(ActivityThread.java:1121) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.app.ActivityThread$PackageInfo.getServiceDispatcher(ActivityThread.java:1016) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.app.ContextImpl.bindService(ContextImpl.java:863) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.content.ContextWrapper.bindService(ContextWrapper.java:347) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at com.flax.trainer.RunOnly.butonStartClickHandler(RunOnly.java:85) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at java.lang.reflect.Method.invoke(Method.java:521) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.view.View$1.onClick(View.java:2067) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.view.View.performClick(View.java:2408) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.view.View$PerformClick.run(View.java:8816) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.os.Handler.handleCallback(Handler.java:587) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.os.Handler.dispatchMessage(Handler.java:92) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.os.Looper.loop(Looper.java:123) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at android.app.ActivityThread.main(ActivityThread.java:4627) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at java.lang.reflect.Method.invoke(Method.java:521) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
09-10 18:28:18.352: ERROR/ActivityThread(905):  at dalvik.system.NativeStart.main(Native Method) 
+0

好的,所以你想要在任何時候運行這個服務,即使應用程序關閉了嗎? – xil3 2010-09-10 15:51:47

+0

不,當我按下按鈕我回到我的主要活動。我不關閉我的應用程序,只是回到主要活動。感謝 – Jovan 2010-09-10 15:53:58

+0

我在所有活動的onStart()方法中綁定到服務,然後在onStop()中解除綁定。下一個activity的onStart()在最後一個activity的onStop()之前被調用。 – onitake 2011-04-26 13:37:53

回答

4

如果使用BIND_AUTO_CREATE標誌比當活動被關閉您的服務將被銷燬。 你應該在bindService()之前使用startService()來阻止這個