Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> android中application 關於全局變量

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代碼

  1. public class TestApplication extends Application {

  2.

  3. private int curIndex;

  4.

  5. public int getCurIndex() {

  6. return curIndex;

  7. }

  8.

  9. public void setCurIndex(int curIndex) {

  10. this.curIndex = curIndex;

  11. }

  12.

  13. @Override

  14. public void onCreate() {

  15. super.onCreate();

  16. }

  17.

  18. @Override

  19. public void onTerminate() {

  20. super.onTerminate();

  21. }

  22.

  23. }

  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());

  在運行過程中,每一次都kill掉對應的Activity,再進入下一個Activity。運行的結果如下:

  < !--StartFragment -->

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved