定义全局变量

找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。
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()方法获取这个实例,进而获取其中的状态(变量)。

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(); … } } 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. Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原
  2. chromium for android Browser进程结构分析
  3. Android应用程序级变量(全局变量)
  4. android sudio 快捷键
  5. 《Android(安卓)高性能编程》—— @IntDef 注解,减缓枚举的使用
  6. Windos下Android(ADT Bundle)配置NDK的两种方法------ADT、Cygwin
  7. Android(安卓)OpenSSL分析及实例
  8. 【Android每日点滴】Fragment与Activity交互
  9. Android(安卓)GreenDao 3.0使用实例讲解

随机推荐

  1. Android 基础教程之-------Android Progr
  2. Android Input System分析(一)--基本架构
  3. 如果谷歌以微软为鉴,它就不会去搞什么Andr
  4. 初探Android 热修复
  5. [Android] property_get/property_set
  6. 高焕堂讲解之 Intent-based Programming
  7. Android中View的知识体系——(3)View的事件
  8. Google官方usb开发教程理解
  9. [Android] ListView中getView的原理+如何
  10. Android小项目————聊天室(UI篇)