La actividad <Nombre de la aplicación> ha filtrado ServiceConnection <ServiceConnection Name> @ 438030a8 que estaba vinculada originalmente aquí

Estoy trabajando en mi primera aplicación de Android. Tengo tres actividades en mi aplicación, y el usuario cambia de un lado a otro con bastante frecuencia. También tengo un servicio remoto, que maneja una conexión telnet. Las aplicaciones deben enlazar a este servicio para enviar / recibir mensajes telnet.

Editar Gracias BDLS por su respuesta informativa. He re-escrito mi código a la luz de su aclaración sobre la diferencia entre el uso de bindService () como una función autónoma o después de startService (), y ahora sólo obtener el mensaje de error de fugas de forma intermitente cuando se utiliza el botón volver a ciclo entre ocupaciones.

Mi actividad de conexión tiene los siguientes onCreate () y onDestroy ():

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Initialize the ServiceConnection. Note that this is the only place startService() is run. * It is also the only time bindService is run without dependency on connectStatus. */ conn = new TelnetServiceConnection(); //start the service which handles telnet Intent i = new Intent(); i.setClassName( "com.wingedvictorydesign.LightfactoryRemote", "com.wingedvictorydesign.LightfactoryRemote.TelnetService" ); startService(i); //bind to the service bindService(i, conn, 0); setContentView(R.layout.connect); setupConnectUI(); }//end OnCreate() @Override protected void onDestroy() { super.onDestroy(); //unbind the service and null it out if (conn != null) { unbindService(conn); conn = null; } if(connectStatus == 0) { //stop the service Intent i = new Intent(); i.setClassName( "com.wingedvictorydesign.LightfactoryRemote", "com.wingedvictorydesign.LightfactoryRemote.TelnetService" ); stopService(i); Log.d("LightfactoryRemote", "Connect onDestroy() attempted to stop service"); } Log.d("LightfactoryRemote", "Connect onDestroy()"); }//end onDestroy() 

Así que el servicio se inicia cuando se inicia la actividad y se detiene cuando se destruye la actividad si no se ha logrado una conexión telnet satisfactoria (connectStatus == 0). Las otras actividades se enlazan al servicio sólo si se ha realizado una conexión satisfactoria (connectStatus == 1, guardado en las preferencias compartidas). Aquí está su onResume () y onDestroy ():

 @Override protected void onResume() { super.onResume(); //retrieve the shared preferences file, and grab the connectionStatus out of it. SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_WORLD_WRITEABLE); connectStatus = settings.getInt("connectStatus", 0); Log.d("LightfactoryRemote", "Focus onResume with " + connectStatus); //if a telnet connection is active, start the service and bind to it if (connectStatus == 1) { conn = new TelnetServiceConnection(); Intent i = new Intent(); i.setClassName("com.wingedvictorydesign.LightfactoryRemote", "com.wingedvictorydesign.LightfactoryRemote.TelnetService"); bindService(i, conn, 0); //TODO write restore texview code }//end if }//end onResume @Override protected void onDestroy() { super.onDestroy(); //unbind the service and null it out. if (conn != null) { Log.d("LightfactoryRemote", "Focus onDestroy() attempted to unbind service"); unbindService(conn); conn = null; } Log.d("LightfactoryRemote", "Focus onDestroy()"); }//end onDestroy() 

Por lo tanto, la vinculación ocurre en onResume () para que capte el estado cambiado de la actividad de conexión, y en la función onDestroy () es unbound, si es necesario.

End Edit

Pero todavía consigo el mensaje de error de la fuga de memoria "La actividad ha filtrado ServiceConnection @ 438030a8 que fue limitado originalmente aquí" intermitentemente al cambiar actividades. ¿Qué estoy haciendo mal?

Gracias de antemano por cualquier sugerencia o punteros!

Aparece un mensaje de error completo (del código revisado):

 01-02 22:04:26.642: DEBUG/LightfactoryRemote(2024): Focus onStop() 01-02 22:04:26.642: DEBUG/LightfactoryRemote(2024): Focus onDestroy() attempted to unbind service 01-02 22:04:26.642: DEBUG/LightfactoryRemote(2024): Focus onDestroy() 01-02 22:04:26.672: ERROR/ActivityThread(2024): Activity com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote has leaked ServiceConnection com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote$TelnetServiceConnection@439e51e8 that was originally bound here 01-02 22:04:26.672: ERROR/ActivityThread(2024): android.app.ServiceConnectionLeaked: Activity com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote has leaked ServiceConnection com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote$TelnetServiceConnection@439e51e8 that was originally bound here 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread$PackageInfo$ServiceDispatcher.<init>(ActivityThread.java:927) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread$PackageInfo.getServiceDispatcher(ActivityThread.java:822) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ApplicationContext.bindService(ApplicationContext.java:842) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.content.ContextWrapper.bindService(ContextWrapper.java:319) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote.onResume(LightfactoryRemote.java:102) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1225) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.Activity.performResume(Activity.java:3559) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2838) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2866) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.os.Handler.dispatchMessage(Handler.java:99) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.os.Looper.loop(Looper.java:123) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at android.app.ActivityThread.main(ActivityThread.java:4203) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at java.lang.reflect.Method.invokeNative(Native Method) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at java.lang.reflect.Method.invoke(Method.java:521) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 01-02 22:04:26.672: ERROR/ActivityThread(2024): at dalvik.system.NativeStart.main(Native Method) 01-02 22:04:26.692: WARN/ActivityManager(558): Unbind failed: could not find connection for android.os.BinderProxy@43c509a8 

Editar el segundo
Gracias de nuevo bdls por sus sugerencias. Hice lo que usted sugirió y agregó un onUnBind () anular al servicio. OnUnBind () en realidad sólo se activa cuando todos los clientes se desconectan del servicio, pero cuando me golpeó el botón de inicio, se ejecutó, a continuación, el mensaje de error apareció! Esto no tiene ningún sentido para mí, ya que todos los clientes han sido desvinculados del servicio, así que ¿cómo podría destruir una fuga un serviceConnection? Echale un vistazo:

 01-03 19:38:30.837: DEBUG/LightfactoryRemote(1118): Focus onPause()1 01-03 19:38:31.577: WARN/IInputConnectionWrapper(1118): showStatusIcon on inactive InputConnection 01-03 19:38:31.587: DEBUG/LightfactoryRemote(1118): Focus onStop() 01-03 19:38:31.600: DEBUG/LightfactoryRemote(1118): Focus onDestroy() attempted to unbind service 01-03 19:38:31.607: DEBUG/LightfactoryRemote(1118): Focus onDestroy() 01-03 19:38:31.677: DEBUG/LightfactoryRemote(1125): TelnetService onUnBind() 01-03 19:38:31.727: ERROR/ActivityThread(1118): Activity com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote has leaked ServiceConnection com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote$TelnetServiceConnection@435baeb0 that was originally bound here 01-03 19:38:31.727: ERROR/ActivityThread(1118): android.app.ServiceConnectionLeaked: Activity com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote has leaked ServiceConnection com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote$TelnetServiceConnection@435baeb0 that was originally bound here 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread$PackageInfo$ServiceDispatcher.<init>(ActivityThread.java:886) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread$PackageInfo.getServiceDispatcher(ActivityThread.java:781) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ApplicationContext.bindService(ApplicationContext.java:820) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.content.ContextWrapper.bindService(ContextWrapper.java:307) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at com.wingedvictorydesign.LightfactoryRemote.LightfactoryRemote.onResume(LightfactoryRemote.java:102) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1225) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.Activity.performResume(Activity.java:3530) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2619) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2287) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread.access$1800(ActivityThread.java:112) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.os.Handler.dispatchMessage(Handler.java:99) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.os.Looper.loop(Looper.java:123) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at android.app.ActivityThread.main(ActivityThread.java:3948) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at java.lang.reflect.Method.invokeNative(Native Method) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at java.lang.reflect.Method.invoke(Method.java:521) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540) 01-03 19:38:31.727: ERROR/ActivityThread(1118): at dalvik.system.NativeStart.main(Native Method) 01-03 19:38:31.777: WARN/ActivityManager(564): Unbind failed: could not find connection for android.os.BinderProxy@4370f8a8 

Pensé que podría ser algo como usted dijo, donde la vinculación al servicio no es completa cuando unbindService () se llama, sin embargo, traté de llamar a un método en el servicio como yo respaldado a través de cada actividad para verificar que la vinculación es completa, y Todos pasaron bien.

En general, este comportamiento no parece relacionado con cuánto tiempo permanezco en cada actividad. Una vez que la primera actividad pierde su servicio de conexión, sin embargo, todos lo hacen como yo de nuevo a través de ellos después de eso.

Otra cosa, si activar "Destruir actividades inmediatamente" en Herramientas de desarrollo, evita este error.

¿Algunas ideas?

No ha proporcionado ninguna de su código de LightFactoryRemote , por lo que esto es sólo una presunción, pero parece que el tipo de problema que estaría viendo si estaba utilizando el método bindService en su propio.

Para garantizar que un servicio se mantiene en funcionamiento, incluso después de que la actividad que se inició ha tenido su método onDestroy llamado, primero debe utilizar startService .

Los documentos android para el estado startService :

El uso de startService () reemplaza la vida útil predeterminada administrada por bindService (Intent, ServiceConnection, int): requiere que el servicio siga funcionando hasta que se llama a stopService (Intent), independientemente de si hay clientes conectados a él.

Considerando que para bindService :

El servicio se considerará requerido por el sistema sólo durante el tiempo que exista el contexto de llamada. Por ejemplo, si este Contexto es una Actividad que se detiene, no se requerirá que el servicio continúe funcionando hasta que se reanude Actividad.


Así que lo que sucedió es la actividad que enlazó (y por lo tanto inició) el servicio, se ha detenido y por lo tanto el sistema piensa que el servicio ya no es necesario y provoca ese error (y luego probablemente detiene el servicio).


Ejemplo

En este ejemplo, el servicio debe mantenerse en ejecución independientemente de si la actividad de llamada se está ejecutando.

 ComponentName myService = startService(new Intent(this, myClass.class)); bindService(new Intent(this, myClass.class), myServiceConn, BIND_AUTO_CREATE); 

La primera línea inicia el servicio y la segunda lo vincula a la actividad.

Usted se une en onResume pero unbind en onDestroy . Debe hacer el onPause en onPause en onPause lugar, de modo que siempre hay pares coincidentes de bind / unbind llamadas. Sus errores intermitentes serán donde su actividad se detiene pero no se destruye, y luego se reanuda de nuevo.

Puedes usar:

 @Override public void onDestroy() { super.onDestroy(); if (mServiceConn != null) { unbindService(mServiceConn); } } 

Sólo debe desvincular el servicio en onDestroy() . Entonces, la advertencia irá.

Vea aquí .

Como intenta explicar el Documento de actividad, hay tres grupos principales de vinculación / desvinculación que utilizarás: onCreate () y onDestroy (), onStart () y onStop () y onResume () y onPause ().

Mencionas que el usuario cambia entre Actividades muy rápidamente. ¿Podría ser que usted está llamando unbindService antes de que la conexión de servicio se ha establecido? Esto puede tener el efecto de no desenclavar, y luego la fuga de la encuadernación.

No está completamente seguro de cómo podría manejar esto … Tal vez cuando se llama onServiceConnected se podría llamar unbindService si onDestroy ya ha sido llamado. No estoy seguro si eso funcionará.


Si aún no lo ha hecho, podría agregar un método onUnbind a su servicio. De esta forma, puede ver exactamente cuándo se desvincularán sus clases y podría ayudar con la depuración.

 @Override public boolean onUnbind(Intent intent) { Log.d(this.getClass().getName(), "UNBIND"); return true; } 

Intente usar unbindService () en OnUserLeaveHint (). Evita que el escenario filtrado ServiceConnection y otras excepciones.
Lo usé en mi código y funciona bien.

Cada servicio que está enlazado en actividad debe desvincularse en el cierre de la aplicación.

Así que intenta usar

  onPause(){ unbindService(YOUR_SERVICE); super.onPause(); } 

Sólo puede controlarlo con un booleano, por lo que sólo se llama unbind si se ha hecho bind

 public void doBindService() { if (!mIsBound) { bindService(new Intent(this, DMusic.class), Scon, Context.BIND_AUTO_CREATE); mIsBound = true; } } public void doUnbindService() { if (mIsBound) { unbindService(Scon); mIsBound = false; } } 

Si sólo desea desvincularla si se ha conectado

 public ServiceConnection Scon = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder binder) { mServ = ((DMusic.ServiceBinder) binder).getService(); mIsBound = true; } public void onServiceDisconnected(ComponentName name) { mServ = null; } }; 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.