什么时候应该使用unregisterReceiver?在onPause()onDestroy()onStop()中?

注意:我需要该服务在后台运行。

更新:

  • 我收到释放接收者null的异常。
  • Activity 泄漏了意图接收者,如果您缺少对unregisterReceiver();的调用

  • 请告诉我是否有问题,这是我的代码:
    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());
        }
    
    }
    

    最佳答案

    这取决于您在哪里注册接收器。互补方法对是

    onCreate - onDestroy
    onResume - onPause
    onStart  - onStop
    

    如果您在第一个接收器中注册接收器,然后在其结束方法中注销它。

    07-24 14:57