Obtener contexto en un Servicio


¿Hay alguna forma confiable de obtener un Context de un Service?

Quiero registrar un receptor de difusión para ACTION_PHONE_STATE_CHANGED pero no necesito mi aplicación para obtener siempre esta información, así que no la pongo en el Manifest.

Sin embargo, no puedo hacer que el receptor de transmisión sea asesinado por el GC cuando necesito esta información, así que estoy registrando el receptor de transmisión en un Service.

Por lo tanto, necesito un Context para llamar a registerReceiver(). Cuando ya no necesito el ACTION_PHONE_STATE_CHANGED I unregister se.

¿Algún consejo?

Author: senshin, 2011-06-23

4 answers

El servicio es un Contexto

 668
Author: mibollma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-04 13:14:27

Service extiende ContextWrapper que extiende el Contexto. Por lo tanto, el Servicio es un Contexto. Utilice la palabra clave 'this' en el servicio.

 48
Author: user2138983,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-06 08:23:04
  1. El servicio extiende ContextWrapper
  2. ContextWrapper extiende el Contexto

So....

Context context = this;

(en Clase de Servicio o Actividad)

 24
Author: Hardik Gajera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 09:13:08

Dado que Service es un Context, la variable context debe ser this:

DataBaseManager dbm = Utils.getDataManager(this);   
 7
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-07 18:37:24