SoFunction
Updated on 2025-03-08

How to use singleton mode in Android studio

This article briefly introduces how to use singleton mode and usage precautions in Android studio.

Singleton mode

Why use singleton mode?

There are some objects that we only need one, only one thread pool, cache, or only one printer, robot, or robot. We can implement it through global static variables, but creating global variables at the beginning of the program may be resource-consuming and may not be useful. Singleton mode is as convenient as global variables without its disadvantages.

Use the single profit mode

public class Sensor {

  // Use static variables to record unique instances  private static Sensor sensorInstance;

  /**
    * Private construction method
    */
  private Sensor(){}

  /**
    * Instantiation method
    * @return Sersor
    * synchronized package will not enter at the same time.
    */
  public static synchronized Sensor getSersorInstance(){
    if(sensorInstance == null) {
       sensorInstance = new Sensor();
    }
    // Return the Sensor unique instance    return sensorInstance;
  }

}

But if you want to create an example in a hurry, and the burden of creating an example is not heavy.

public class Sensor {

  private static Sensor sensorInstance = new Sensor();

  private Sensor(){}

  public static Sensor getSersorInstance(){
    return sensorInstance;
  }
}

If many threads frequently use getSersorInstance, it may affect performance. You can use double check to add lock

public class Sensor {

  // volatile ensures that sensorInstance is initialized and multiple threads are handled correctly  private volatile static Sensor sensorInstance;
  
  private Sensor(){}
  
  public static Sensor getSersorInstance(){
    // Check whether sensorInstance exists. If it does not exist, enter the synchronous block    
    if(sensorInstance == null) {
      // The code in the synchronization block will be executed only on the first time      synchronized() {
        if(sensorInstance == null) {
          sensorInstance = new Sensor();
        }
      }
    }
    return sensorInstance;
  }

}

Memory leak problem in Android

1. When instantiating, we often need to pass in some parameters, such as Context

Then it went smoothly

Sensor sensor = ();

Then there was a serious problem. Sensor singleton held this object of MainActivity, so when we jumped to other Activity pages, the MainActivity object still cannot be released and cannot be recycled.

So we should use context in Application

2. Also in urgent ways

public class Sensor {

    public static final Sensor SENSOR_INSTANCE = new Sensor();
    private List<MyListener> mListenerList;

    private Sensor() {
      mListenerList = new ArrayList<MyListener>();
    }

    public static Sensor getInstance() {
      return SENSOR_INSTANCE;
    }

    public void registerListener(MyListener listener) {
      if (!(listener)) {
        (listener);
      }
    }
    public void unregisterListener(MyListener listener) {
      (listener);
    }
  }

  interface MyListener {
    public void onSomeThingHappen();
  }

MainActivity:

public class MainActivity extends Activity {

    private MyListener mMyListener=new MyListener() {
      @Override
      public void onSomeThingHappen() {
      }
    };

    private Sensor sensor = ();
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      (savedInstanceState);
      setContentView(.activity_main);
      (mMyListener);
    }
}

Objects (mListenerList) of non-static inner class (Sensor) will hold references to external class object (mMyListener). Therefore, the external class object (mMyListener) is held. It will not be recycled and the memory leaks, so it is necessary

@Override
  protected void onDestroy() {
    (mMyListener);
    ();
  }

The above is the detailed content of how to use singleton mode in Android studio. For more information about using singleton mode in Android studio, please follow my other related articles!