嗨我有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);
}
答案 0 :(得分:1)
不,根据文档 - 您必须在onDestroy
方法中取消注册接收者。
onDestroy
来通知服务它已不再使用且正在被删除。该服务应该清理它所拥有的任何资源(线程,已注册的接收器等)。 ... 的
答案 1 :(得分:1)
Actullay no,例如,如果您使用活动onCreate
在context
(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();
}