转自:http://blog.csdn.net/leilu2008/article/details/6199961

android中application 关于全局变量


android编程中,application这样的名词似乎变得那样的不常见,而让大家更为熟悉的是activity、intent、provider、broadcast和service。但其实android中的application也有着它自身的用处。

  打开manifest文件,会看到有一个application配置标签,这就是有关application的使用了。那究竟application有什么用处呢?来看看SDK中是如何描述的:

  Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's < application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

  就是说application是用来保存全局变量的,并且是在package创建的时候就跟着存在了。所以当我们需要创建全局变量的时候,不需要再像 j2se那样需要创建public权限的static变量,而直接在application中去实现。只需要调用Context的 getApplicationContext或者Activity的getApplication方法来获得一个application对象,再做出相应的处理。

  因小工程中涉及到的文件比较多,这里就贴代码撒。

  application文件:

  Java代码



  public class TestApplication extends Application {

  private int curIndex;

  public int getCurIndex() {

  return curIndex;

  }

  public void setCurIndex(int curIndex) {

  this.curIndex = curIndex;



  }

  @Override

  public void onCreate() {

  super.onCreate();

  }

  @Override

  public void onTerminate() {

  super.onTerminate();

  }

  }

  application中有一个curIndex和setter getter方法。

  第一个acitivty中对application进行的操作:

  Java代码

  1. TestApplication application = (TestApplication) this.getApplication();

  2. Log.i("data", ""+application.getCurIndex());

  3. application.setCurIndex(5);

  TestApplication application = (TestApplication) this.getApplication();

  Log.i("data", ""+application.getCurIndex());

  application.setCurIndex(5);

  第二个Activity:

  Java代码

  1. TestApplication application = (TestApplication)this.getApplication();

  2. Log.i("data", ""+application.getCurIndex());

  3. application.setCurIndex(6);

  TestApplication application = (TestApplication)this.getApplication();

  Log.i("data", ""+application.getCurIndex());

  application.setCurIndex(6);

  第三个Activity:

  Java代码

  1. final TestApplication application = (TestApplication) this.getApplication();

  2. Log.i("data", ""+application.getCurIndex());

  final TestApplication application = (TestApplication) this.getApplication();

  Log.i("data", ""+application.getCurIndex());



PS: <application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".TestApplication">

更多相关文章

  1. Android中解析xml文件的接口
  2. Android 各种类型的资源 文件
  3. Android代码中运行shell命令
  4. android中 代码实现截图功能(静态+动态视频)
  5. Android获取cpu和内存信息、网址的代码
  6. Android Studio 配置SVN 及 代码管理
  7. Android中拍照、图片、录音、视频和音频功能的方法和代码
  8. Android文件关联

随机推荐

  1. android 多媒体部分学习笔记十--简单视频
  2. android 让 webview 支持HTML中的
  3. Android(安卓)7.0使用相机功能
  4. Android读取联系人的姓名及号码
  5. Android用代码安装APK,不用选择“打包安
  6. Android(安卓)防止锁屏服务暂时停止运行
  7. android 判断手机是否支持前置摄像头
  8. android创建数据库(SQLite)保存图片示例
  9. android练习一之拨号实现
  10. 【Android】Activity 的 Title 中加入进