阅读更多

The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.

--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。

As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.
--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。

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 andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):
--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。

给个例子:

  1. class MyApp extends Application {

  2.   private String myState;

  3.   public String getState(){
  4.     return myState;
  5.   }
  6.   public void setState(String s){
  7.     myState = s;
  8.   }
  9. }

  10. class Blah extends Activity {

  11.   @Override
  12.   public void onCreate(Bundle b){
  13.     ...
  14.     MyApp appState = ((MyApp)getApplicationContext());
  15.     String state = appState.getState();
  16.     ...
  17.   }
  18. }
复制代码



This has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes).
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。

原文链接:http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables

更多相关文章

  1. 箭头函数的基础使用
  2. NPM 和webpack 的基础使用
  3. Python list sort方法的具体使用
  4. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  5. android PreferenceScreen使用笔记
  6. Android使用Volley保持与服务器的会话
  7. android使用HTTP协议读取数据
  8. android density
  9. Android(安卓)tips tool 发现的性能问题

随机推荐

  1. Handling Android 2.3 WebView's broken
  2. Android Unable to resolve target "Andr
  3. Android EditText默认不弹出输入法
  4. Android SQLite操作类--封装
  5. Android(安卓)常见面试题
  6. Twitter V1.1在Android中的应用
  7. Android低内存配置
  8. Android读取xxx.properties配置文件中文
  9. 保持在底部的按钮栏,上面是滚动的ScrollVi
  10. android studio 项目的版本问题