简体   繁体   English

Android的多个活动访问一个Java类

[英]Android multiple activities access one java class

I am new to android development and appreciate any help. 我是android开发的新手,感谢您的帮助。 I have multiple android activities that have to access one java class. 我有多个Android活动,必须访问一个Java类。 This class has synchronized getters and setters, but I'm having problems making a single instance of this class across the activities. 此类具有同步的getter和setter,但在跨活动创建此类的单个实例时遇到了问题。 Is there any way to easily do this? 有什么办法可以轻松做到这一点?

What you need is a 'singleton' pattern: 您需要的是“单一”模式:

public final class Singleton {
    private final static Singleton ourInstance = new Singleton();
    public static Singleton getInstance() {
        return ourInstance;
    }

    // Contructor is private, so it won't be possible 
    // to create instance of this class from outside of it.
    private Singleton() {
    }
}

Now in your child classes, just use: 现在在您的子班中,只需使用:

Singleton.getInstance()

to access one, single object of this class. 访问此类的单个对象。

you can use singleton design pattern. 您可以使用单例设计模式。 Here is one way of implementing it in java 这是用Java实现的一种方法

public class Singleton 
{
  private static Singleton uniqInstance;

  private Singleton() 
  {
  }

  public static synchronized Singleton getInstance() 
  {
    if (uniqInstance == null) {
      uniqInstance = new Singleton();
    }
  return uniqInstance;
  } 
 // other useful methods here
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM