¿Cuándo anular el registro de BroadcastReceiver? En onPause(), onDestroy(), o onStop()?


¿Cuándo debo usar unregisterReceiver? En onPause(), onDestroy(), o onStop()?

Nota: Necesito que el servicio se ejecute en segundo plano.

Actualización:

  1. Obtengo una excepción liberando receptores null.

  2. La actividad se ha filtrado receptores de intención ¿te falta llamada a unregisterReceiver();

Por favor dime si hay algo mal, aquí está mi código:

private boolean processedObstacleReceiverStarted;
private boolean mainNotificationReceiverStarted;

protected void onResume() {

    super.onResume();
    try {
        registerReceivers();

    } catch (Exception e) {

        Log.e(MatabbatManager.TAG,
                "MAINActivity: could not register receiver for Matanbbat Action "
                        + e.getMessage());
    }
}

private void registerReceivers() {

    if (!mainNotificationReceiverStarted) {
        mainNotificationReceiver = new MainNotificationReceiver();

        IntentFilter notificationIntent = new IntentFilter();

        notificationIntent
                .addAction(MatabbatManager.MATABAT_LOCATION_ACTION);
        notificationIntent
                .addAction(MatabbatManager.MATABAT_New_DATA_RECEIVED);
        notificationIntent
                .addAction(MatabbatManager.STATUS_NOTIFCATION_ACTION);
        registerReceiver(mainNotificationReceiver, notificationIntent);

        mainNotificationReceiverStarted = true;

    }

    if (!processedObstacleReceiverStarted) {
        processedObstacleReceiver = new ProcessedObstacleReceiver();
        registerReceiver(processedObstacleReceiver, new IntentFilter(
                MatabbatManager.MATABAT_ALARM_LOCATION_ACTION));
        processedObstacleReceiverStarted = true;

    }

}

private void unRegisterReceivers() {

    if (mainNotificationReceiverStarted) {
        unregisterReceiver(mainNotificationReceiver);
        mainNotificationReceiverStarted = false;
    }
    if (processedObstacleReceiverStarted) {
        unregisterReceiver(processedObstacleReceiver);
        processedObstacleReceiverStarted = false;
    }

}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    try {

        unRegisterReceivers();
        mWakeLock.release();//keep screen on
    } catch (Exception e) {
        Log.e(MatabbatManager.TAG, getClass() + " Releasing receivers-" + e.getMessage());
    }

}
Author: kcoppock, 2014-01-15

4 answers

Depende de dónde haya registrado el receptor. Los pares de métodos complementarios son

onCreate - onDestroy
onResume - onPause
onStart  - onStop

Si registra el receptor en el primero, anule el registro en su método final.

 74
Author: stinepike,
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-01-15 12:08:46

De la documentación de Android :

Debe implementar onStop () para liberar recursos de actividad como un conexión de red o para anular el registro de receptores de difusión.

Entonces, seguiría estos pares (usando la analogía de @StinePike):

onResume - onPause
onStart  - onStop

Debido al Ciclo de vida de Android , y como @ w3bshark mencionó:

En dispositivos post-HoneyComb (3.0+), onStop() es el último manejador garantizado.

 8
Author: Evin1_,
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
2017-10-18 04:24:01

Un receptor de difusión es un componente invisible. Todo lo que hace es responder a algún tipo de cambio a través de la devolución de llamada onReceive ().

Así que tiene sentido activarlos , solo cuando su actividad está en un estado para responder o cuando se está activando /activando, que es cuando se llama a onResume ().

Así que es una mejor práctica registrarse en onResume() - Cuando la actividad está visible y Habilitada y anular el registro en onStop() cuando la actividad ya no está Activa.

 1
Author: WonderBoy,
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-24 00:03:13

Es tan simple como eso, si desea escuchar eventos incluso cuando su actividad no es visible, llame a unregister en onStop() (Por ejemplo, desde la Actividad A se abre la Actividad B, pero si desea A seguir escuchando los eventos).

Pero cuando solo desea escuchar solo eventos cuando su actividad es visible, entonces en onPause llame a unregister() (Por ejemplo, desde la Actividad A abriste la Actividad B pero ahora no quieres escuchar los eventos de la actividad A).

Espero que esto ayude a su problema.

 1
Author: Sudhanshu Gaur,
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
2017-08-03 14:18:36