android中使用static 类造成的问题

static 类使用场景-单例模式

java中经常会使用单例模式,单例模式保证内存中同一时间只有一个类的对象,如:

public class AutoTestModuleManager{

    private static AutoTestModuleManager mAutoTestMdManager = null;
    private Map mUiList = null;

    private AutoTestModuleManager() {
        Log.w("test","AutoTestModuleManager");
        if(null == mUiList){
            mUiList = new HashMap();
        }
        mUiList.clear();
    }
    public synchronized static AutoTestModuleManager getInstance() {
        if (null == mAutoTestMdManager) {
            mAutoTestMdManager = new AutoTestModuleManager();
            SkLog.e("getInstance");
        }

        return mAutoTestMdManager;
    }
}

单例模式就是使用static 类,上述代码的getInstance获取AutoTestModuleManager 的单一对象。还有下面一种俗称双重检查锁定的单例模式:

public class Singleton {  
      private volatile static Singleton singleton;  
      private Singleton (){}   
      public static Singleton getSingleton() {  
      if (singleton == null) {  
          synchronized (Singleton.class) {  
         if (singleton == null) {  
              singleton = new Singleton();  
          }  
         }  
    }  
     return singleton;  
     }  
}  

android中使用static类易出现的问题

在android中使用static类需要注意,如果apk退出时程序员未主动释放static类,将造成内存泄漏。如上述AutoTestModuleManager类,如果在activity中调用,当activity onPause-》onStop-》onDestory退出后,AutoTestModuleManager静态对象并没有被销毁,这时如果再次进入activity,会发现AutoTestModuleManager的构造函数并没有被执行,也就是说AutoTestModuleManager静态对象没有重新生成。
出现这种问题带来的不仅仅是内存泄漏的危害,对我们的程序运行逻辑也是有意料不到的影响。比如我们在activity中调用静态类,希望在activity调用的时候能初始化该类,但是如果activity退出的时候没有释放静态类,当再次启动activity时,静态类没有初始化,而是沿用的上一次的,这样就会带来问题。

解决办法

在使用静态类时要注意使用完后释放,如上述AutoTestModuleManager类中,增加release接口:

public synchronized void release(){
        if(mUiList != null){
            mUiList.clear();
        }
        mUiList = null;
        mAutoTestMdManager = null;
    }

activity中使用完AutoTestModuleManager后调用release()即可。

你可能感兴趣的:(android,java)