代码之家  ›  专栏  ›  技术社区  ›  N Sharma

如果服务被破坏,广播接收器也会注销吗

  •  0
  • N Sharma  · 技术社区  · 8 年前

    嗨,我有 Service 我正在注册广播接收器的位置。我想知道服务是否被破坏,然后我添加的广播接收器是否也未注册。

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        locationManager.addProximityAlert(
                latitude, // the latitude of the central point of the alert region
                longitude, // the longitude of the central point of the alert region
                radius, // the radius of the central point of the alert region, in meters
                -1, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
                proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
        );
    
        IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
        registerReceiver(new ProximityIntentReceiver(), filter);
    
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        locationManager.removeUpdates(listener);
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   RadekJ    8 年前

    否,根据文档,您必须在中注销收件人 onDestroy 方法

    销毁 由系统调用,以通知服务它已不再使用并且正在删除。服务应该清理它所持有的任何资源(线程、, 注册接收人 ,等等)在这一点上。。。

        2
  •  1
  •   Adil    8 年前

    实际上,否,您在其中注册和注销收件人,例如,如果您在中注册收件人 onCreate (捆绑)使用活动的 context ,您应该在中注销它 onDestroy() 防止接收器泄漏到活动上下文之外。如果您在 onResume() ,您应该在中注销它 onPause() 防止多次注册(如果您不想在暂停时接收广播,这可以减少不必要的系统开销)。请勿在中注销 onSaveInstanceState (Bundle),因为如果用户在历史堆栈中向后移动,则不会调用此函数。 for more help refer this

    public void unregisterBroadcastReceiver() {
    
        this.unregisterReceiver(broadCastReceiver);
    
        Toast.makeText(this, 'unregistered broadcst receiver', Toast.LENGTH_SHORT)
          .show();
       }