Android has a lot of registration and anti-registration, because after registration, it will be persisted in the observer list, if not anti-registration, will cause a memory leak
memory leaks 1:sensor Manager
The code is as follows:
Mainactivity.java
void registerListener() { SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ALL); sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);}View smButton = findViewById(R.id.sm_button);smButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerListener(); nextActivity(); }});
why not?
Call Getsystemservice through the context to get system services that run in their own processes performing a series of background work or interfaces that provide and hardware interaction, if the context object needs to be notified at any time when an internal service event occurs. You need to register yourself as a listener so that the service holds an activity, and if the developer forgets to log off the listener before the activity is destroyed, it causes a memory leak.
How to solve?
Unregisters the listener in the OnDestroy method.
Android Memory optimization 12 memory leaks common scenario 3 registration persistence