Android中的单身人士

我已经跟随这个链接,并成功地在Android的单身人士课程。 http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

问题是我想单个对象。 就像我有活动A和活动B.在活动AI从单身人士class访问对象。 我使用该对象并对其进行了一些更改。

当我移动到Activity B并从Singleton Class访问对象时,它给了我初始化的对象,并不保留我在Activity A中所做的更改。是否有其他方法来保存更改? 请帮助我的专家。 这是MainActivity

 public class MainActivity extends Activity { protected MyApplication app; private OnClickListener btn2=new OnClickListener() { @Override public void onClick(View arg0) { Intent intent=new Intent(MainActivity.this,NextActivity.class); startActivity(intent); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Get the application instance app = (MyApplication)getApplication(); // Call a custom application method app.customAppMethod(); // Call a custom method in MySingleton Singleton.getInstance().customSingletonMethod(); Singleton.getInstance(); // Read the value of a variable in MySingleton String singletonVar = Singleton.customVar; Log.d("Test",singletonVar); singletonVar="World"; Log.d("Test",singletonVar); Button btn=(Button)findViewById(R.id.button1); btn.setOnClickListener(btn2); } 

}

这是NextActivity

 public class NextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_next); String singletonVar = Singleton.customVar; Log.d("Test",singletonVar); }} 

Singleton

 public class Singleton { private static Singleton instance; public static String customVar="Hello"; public static void initInstance() { if (instance == null) { // Create the instance instance = new Singleton(); } } public static Singleton getInstance() { // Return the instance return instance; } private Singleton() { // Constructor hidden because this is a singleton } public void customSingletonMethod() { // Custom method } } 

MyApplication

 public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Initialize the singletons so their instances // are bound to the application process. initSingletons(); } protected void initSingletons() { // Initialize the instance of MySingleton Singleton.initInstance(); } public void customAppMethod() { // Custom application method } } 

当我运行这个代码,我得到你好,我已经初始化在Singleton然后世界,我给它在MainActivity并再次显示你在NextActivity logcat。 我希望它在NextActivity再次显示世界。 请帮我解决这个问题。

编辑:

Android中Singleton的实现是不安全的,你应该使用一个专门用于这种模式的库,如Dagger或其他DI库来pipe理生命周期和注入。


你能从你的代码发布一个例子吗?

看看这个要点: https : //gist.github.com/Akayh/5566992

它的工作原理很快就完成了:

MyActivity:首次设置单例+在私有构造函数中初始化mString属性(“Hello”)并显示值(“Hello”)

将新值设置为mString:“Singleton”

启动activityB并显示mString值。 “单身人士”出现…

提示:创build单例类在Android Studio中,右键单击您的项目并打开菜单:

 New -> Java Class -> Choose Singleton from dropdown menu 

在这里输入图像描述

很简单,作为一个java,Android也支持singleton。 –

辛格尔顿是四人帮devise模式的一部分,它被归类为创作devise模式。

– >静态成员:这包含单例类的实例。

– >私有构造函数:这将阻止任何人实例化Singleton类。

– >静态公共方法:这提供了Singleton对象的全局访问点并将实例返回给客户端调用类。

  1. 创build私人实例
  2. 创build私有构造函数
  3. 使用Singleton类的getInstance()

     public class Logger{ private static Logger objLogger; private Logger(){ //ToDo here } public static Logger getInstance() { if (objLogger == null) { objLogger = new Logger(); } return objLogger; } } 

而使用单身 –

 Logger.getInstance(); 

由rakesh提出的答案是伟大的,但仍然有一些解释Android中的Singleton与Java中的Singleton相同:Singletondevise模式解决了所有这些问题。 使用Singletondevise模式,您可以:

1)确保只创build一个类的一个实例

2)提供一个全局访问的对象

3)将来允许多个实例,而不会影响单例类的客户端

一个基本的Singleton类的例子:

 public class MySingleton { private static MySingleton _instance; private MySingleton() { } public static MySingleton getInstance() { if (_instance == null) { _instance = new MySingleton(); } return _instance; } } 

正如@Lazy在这个答案中所说的,你可以在Android Studio中使用模板创build一个单例。 值得注意的是,不需要检查实例是否为空,因为静态的ourInstancevariables是首先初始化的。 因此,Android Studio创build的单例类实现与以下代码一样简单:

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

您将单例的customVar复制到singletonVarvariables中,并且更改该variables不会影响singleton中的原始值。

 // This does not update singleton variable // It just assigns value of your local variable Log.d("Test",singletonVar); singletonVar="World"; Log.d("Test",singletonVar); // This actually assigns value of variable in singleton Singleton.customVar = singletonVar; 

我把我的版本的辛格尔顿下面:

 public class SingletonDemo { private static SingletonDemo instance = null; private static Context context; /** * To initialize the class. It must be called before call the method getInstance() * @param ctx The Context used */ public static void initialize(Context ctx) { context = ctx; } /** * Check if the class has been initialized * @return true if the class has been initialized * false Otherwise */ public static boolean hasBeenInitialized() { return context != null; } /** * The private constructor. Here you can use the context to initialize your variables. */ private SingletonDemo() { // Use context to initialize the variables. } /** * The main method used to get the instance */ public static synchronized SingletonDemo getInstance() { if (context == null) { throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before"); } if (instance == null) { instance = new SingletonDemo(); } return instance; } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not allowed."); } } 

请注意,初始化方法可以在主类(Splash)中调用,方法getInstance可以从其他类中调用。 这将解决问题,当调用者类需要单身人士,但它没有上下文。

最后的方法有BeenInitialized是用来检查类是否已经初始化。 这将避免不同的实例具有不同的上下文。

在Android中使用单例的最简洁和最现代的方法就是使用称为Dagger 2的dependency injection框架。 在这里你可以解释一下你可以使用的范围。 辛格尔顿是这些范围之一。 dependency injection并不是那么容易,但是你应该花一点时间来理解它。 这也使testing更容易。