Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 中使用 Application 實現全域變數共享

編輯:關於 Android 程式設計

在 Android 開發中,我們常常需要一些能在 App 內任何 Activity 或 Service 都能存取的資料。這時,Application 就是一個理想的選擇。

為什麼是 Application

我們的整個應用就是一個 Application,因此在一個 App 裡只會存在一個單例的 Application 實例。用這個單例來存放全域變數,正是它天生的用途。

建立自訂 Application

首先建立一個類別,繼承 android.app.Application:

public class MyApplication extends Application {
    private Integer allViewInteger;
    public Integer getAllViewInteger() { return allViewInteger; }
    public void setAllViewInteger(Integer allViewInteger) { this.allViewInteger = allViewInteger; }
}

在 Manifest 中宣告

接著要在 AndroidManifest.xml 中宣告這個 Application。由於系統預設已有一個 Application,我們只需在 application 標籤中加上 android:name 屬性,指向自訂的類別即可:


用單例模式方便存取

若把共用的 Java 方法寫在 Application 裡,為了方便在沒有 Context 的地方也能存取,可以善用單例設計模式。覆寫 onCreate,在 Application 建立時把自身賦值給一個靜態成員變數:

public class MyApplication extends Application {
    private static MyApplication myApplication = null;
    public static MyApplication getMyApplication() { return myApplication; }
    private Integer allViewInteger;
    public Integer getAllViewInteger() { return allViewInteger; }
    public void setAllViewInteger(Integer allViewInteger) { this.allViewInteger = allViewInteger; }
    @Override public void onCreate() {
        super.onCreate();
        myApplication = this;
    }
}

如此一來,就能在任何地方透過 MyApplication.getMyApplication() 取得這個單例並存取值。以下示範在兩個 Activity 間共享同一個變數——在 MainActivity 中寫入:

MyApplication myApplication = MyApplication.getMyApplication();
myApplication.setAllViewInteger(100);

而在 SecActivity 中讀取:

TextView textView = (TextView) findViewById(R.id.tv_sec);
textView.setText(String.valueOf(MyApplication.getMyApplication().getAllViewInteger()));

透過 Application 這個天然的單例,全域資料的共享變得既簡單又直觀,想存什麼都可以,讀取起來也相當方便。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved