編輯:初階開發
在 Android 開發中,Application 這個名詞相對冷門,大家更熟悉的是 Activity、Intent、Provider、Broadcast 與 Service。但它其實有自己獨特的用途。
打開 manifest 會看到一個 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()。
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();
}
}
別忘了在 AndroidManifest.xml 中註冊:
<application android:name=".TestApplication" ... > ... </application>
漏掉這步,getApplication() 回傳的仍是預設的 Application 物件,轉型就會失敗。
第一個 Activity:
TestApplication application = (TestApplication) this.getApplication();
Log.i("data", "" + application.getCurIndex());
application.setCurIndex(5);
第二個 Activity:
TestApplication application = (TestApplication) this.getApplication();
Log.i("data", "" + application.getCurIndex());
application.setCurIndex(6);
第三個 Activity:
final TestApplication application = (TestApplication) this.getApplication();
Log.i("data", "" + application.getCurIndex());
測試時每進入下一個 Activity 就把前一個 kill 掉,可以看到數值在 Activity 之間完整傳遞,證明 Application 物件確實是進程級別的單例。
Application 的生命周期等於整個進程,因此不宜在其中放置大量資料或長時間持有的資源,否則容易造成記憶體浪費。另外,若App 進程被系統回收後重建,這裡的狀態會歸零;真正需要持久化的資料仍應交給 SharedPreferences 或資料庫。
Android 開發講義(一):Intent 導向程式設計與四大嫡系元件
一、Intent-based Programming:嫡系元件之間如何溝通 Android 的四個嫡系元件——Activity、Service、BroadcastRece
用 Gallery 控件打造遊戲選關界面
遊戲開發中幾乎都會有選關頁面。要實現得快,用 ListView 就夠了;想要效果更出彩,可以選擇 Gallery 控件——它支持手指拖動、點擊選中,天生適合做橫向的關卡列
行動 Web 開發者值得收藏的 9 個框架與工具
行動開發的熱潮從 iPhone 起算,行動瀏覽器對 HTML5、CSS3 與 CSS 動畫的支持也快速成熟;Google 推出 Android 之後,行動平台時代正式成形
Android 特色開發:帳戶管理(AccountManager)實作解析
本文節選自機械工業出版社《Android 應用開發揭秘》,作者楊豐盛。該書涵蓋 Android 框架、組件、使用者介面、遊戲開發、資料儲存、多媒體與網路開發等基礎,並深入