我应该在Application类中使用全局变量,还是在所有活动都扩展的Activity中

时间:2014-03-12 07:52:47

标签: android

现在我需要的所有工具(DatabaseHelper单例,ImageLoader单例,PhotoHandler,自定义Toast Maker)都在我的所有活动扩展的onCreate中初始化,但我刚才意识到每一个新活动开始的时间,这些都会重新实现。

这是一个问题吗?

我是否应该更改为创建扩展Application的类并在其中包含这些变量? 如果是这样,我应该将那个Application类的哪个方法实例化?

为了使图片完整,我还有一个公共静态终结类,它包含各种常量,如错误消息和应用程序首选项

我有一个在用户登录后立即执行的InitialDataLoader类,它从服务器获取用户需要的所有内容并将其存储在本地。

那么哪个应该是我更适合实例化上述工具的地方?

以下是我的所有活动扩展的活动的一部分:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    dbTools = DBTools.getInstance(this);

    // Create global configuration and initialize ImageLoader with this configuration
    // https://github.com/nostra13/Android-Universal-Image-Loader
    ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext()).build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(imageLoaderConfiguration);

    // Set global bitmap preferences
    bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inDither = false;
    bitmapOptions.inPurgeable = true;
    bitmapOptions.inInputShareable = true;
    bitmapOptions.inTempStorage = new byte[16 * 1024];

    // Get an instance of the current user
    instanceOfTheCurrentUser = Transporter.instance().instanceOfTheCurrentUser;

2 个答案:

答案 0 :(得分:2)

我会使用getInstance(Context context)方法使用懒惰的初始化单例(请记住在此方法中仅使用context.getApplicationContext(),否则您将泄漏Activity / Service实例)。对象的生命周期与Application对象的生命周期相同,但您不必对应用程序类进行Context的强制转换:

public class ImageLoader {
  private ImageLoader(Context context) {
  }

  private static final ImageLoader sInstance;
  public synchronized static ImageLoader getInstance(Context context) {
    if (sInstance == null) {
      sInstance = new ImageLoader(context.getApplicationContext());
    }
    return sInstance;
  }
}

答案 1 :(得分:1)

我认为如果你把它们作为静态类会很好..

你可以为每个类创建一个初始化方法(作为构造函数的替换;如果你需要它); 并且当类之前已经初始化时,创建一个标志(例如一个布尔值)..所以即使你多次调用初始化函数(假设每次启动一个活动),它都会没问题。

希望它有所帮助..

相关问题