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

时间:2018-02-06 04:10:06

标签: android

嗨我有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 个答案:

答案 0 :(得分:1)

不,根据文档 - 您必须在onDestroy方法中取消注册接收者。

系统调用

onDestroy来通知服务它已不再使用且正在被删除。该服务应该清理它所拥有的任何资源(线程,已注册的接收器等)。 ...

答案 1 :(得分:1)

Actullay no,例如,如果您使用活动onCreatecontext(Bundle)中注册接收者,则注册和取消注册接收者,您应该在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();
   }