Android中的Singleton是怎么使用的?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (210)

当我移动到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
}
}
提问于
用户回答回答于

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

用户回答回答于

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

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

扫码关注云+社区

领取腾讯云代金券