如何使用吉斯的@Singleton? [英] How to use @Singleton of Guice ?

查看:78
本文介绍了如何使用吉斯的@Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一些类的一个实例 - 这一个实例必须是从code任何地方访问。

I need to make one instance of some class - and this one instance need to be accessible from any place in the code.

于是,我找到了吉斯......,我想用'@Singleton从这个包,但我没有找到任何例子或者一些文档要如何使用它,以及如何作出声明。

So, I found the Guice... and i want to use the '@Singleton' from this package but i don't find any example or some doc to how to use it and how to make the declaration.

推荐答案

好了,我的答案是不特定的吉斯的@Singleton,但如果你想一类,它是通过访问所有的活动,然后我想,你必须使用应用程序类的Andr​​oid。 (这是我个人的看法您的需求)

Ok, My answer is not a specific for @Singleton of Guice, But If you want to Make a class which is accessible through all your activities then I think,You have to use Application class of Android. (This is my personal opinion for your need)

要做到这一点的方法是创建你自己的子类 android.app.Application ,然后指定你的清单中的类应用程序中的标记。现在,Android将自动创建该类的实例,并使其可用于整个应用程序。您可以在任何情况下使用 Context.getApplicationContext()办法(活动还提供了一种访问 getApplication()具有完全相同的效果):

The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):

class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

这有基本相同的效果使用静态变量或单身,但集成了相当不错到现有的Andr​​oid框架。请注意,这不会跨进程的工作(要你的应用程序是稀有的,具有多个进程之一)。

This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).

下面是关于如何使用它,<一个漂亮的教程href="http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/"相对=nofollow>扩展Android应用程序类和处理辛格尔顿

Here is the nice tutorial about how to use it, Extending the Android Application class and dealing with Singleton

这篇关于如何使用吉斯的@Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆