Android Memory optimization 12 memory leaks common scenario 3 registration persistence

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.