當我們需要在整個應用程式中定義全域變數時,可通過擴充 Android 的 Application 類來實現,這裡是一個基礎的類用來操作全域的應用狀態。
下面是建立全域變數的步驟:
1) 建立一個新類擴充自 Application 類:
public class Global extends Application { private Boolean _notification=false; public Boolean get_notification() { return _notification; } public void set_notification(Boolean _notification) { this._notification = _notification; } } public class Global extends Application { private Boolean _notification=false; public Boolean get_notification() { return _notification; } public void set_notification(Boolean _notification) { this._notification = _notification; }
}2) 添加新類到 AndroidManifest 檔案作為 application 標籤的屬性:
<application android:name=".Global" .... /> <applicationandroid:name=".Global" .... />3)
你可通過 Context.getApplicationContext() 方法來訪問到該全域變數:
Global global; public void onCreate(Bundle savedInstanceState) { global=((Global)getApplicationContext()); Boolean notification=global.get_notification();} Global global; public void onCreate(Bundle savedInstanceState) { global=((Global)getApplicationContext()); Boolean notification=global.get_notification();}