关于android中是否可以使用全局变量,当然可以。做Java的人肯定都用过全局变量了,使用方法无非是定义一个静态变量,public类型,这样在其他类中就可以直接调用了,android中也可以这样使用。 但是,android中这样使用全局变量是不是最符合android的架构呢,在国外的论坛里找到了下面的解决办法: 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()方法获取这个实例,进而获取其中的状态(变量)。 下面看一下Demo: 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的架构体系。 使用这种方法的话需要在 AndroidManifest.xml中配置一下:

更多相关文章

  1. android网络编程——使用Android中的网络连接
  2. Android(安卓)Studio 网络调试
  3. Android进程间通信(一):AIDL使用详解
  4. Android适配全攻略(学习笔记总结)
  5. android - 为安全而设计 - 3 - 开发文档翻译
  6. 【Android(安卓)Studio使用教程3】Android(安卓)Studio的一些设
  7. 使用Android(安卓)adb命令来启动Android应用程序
  8. android ndk 开发之 在 应用程序中使用 jni
  9. android SQLite 使用实例

随机推荐

  1. 动画的两种实现模式Animation
  2. Android 启动过程分析 (一)
  3. 深入浅出android/ophone UI实现水平布局
  4. android的Activity之间的数据传递
  5. Android Studio 快捷键大全
  6. 布局资源(layout)的简单使用
  7. Android中Style和Theme的使用总结
  8. Andriod编程入门知识
  9. 使用gdb在Android(安卓)Emulator中进行调
  10. Chris:怎样成为一名Android应用开发者