建立 Application 的子類別,並將其設計成類似於 Singleton Pattern。
將全域資料放到這個子類別中,並提供存取方法。
package com.foxx.utility;
import android.app.Application;
public class ApplicationEx extends Application
{
private static ApplicationEx sUniqueInstance;
public static ApplicationEx getInstance()
{
return sUniqueInstance;
}
@Override
public void onCreate()
{
super.onCreate();
sUniqueInstance = this;
sUniqueInstance.initData();
}
private void initData()
{
//init some data here
}
}
第14行複寫 Application 的 onCreate 方法,該方法的 comment 敘述了幾個重點
/**
* Called when the application is starting, before any activity, service,
* or receiver objects (excluding content providers) have been created.
* Implementations should be as quick as possible (for example using
* lazy initialization of state) since the time spent in this function
* directly impacts the performance of starting the first activity,
* service, or receiver in a process.
* If you override this method, be sure to call super.onCreate().
*/
public void onCreate() {
}
1.onCreate()會在所有 activity , service , receiver 建立之前被呼叫。
2.onCreate()會影響啟動第一個元件的時間。
3.onCreate()記得呼叫 super.onCreate()。
4.記得在AndroidManifest.xml 指定使用 Application name
<application
...
android:name="com.foxx.utility.ApplicationEx"
...
>
顯而易見的好處是當你需要 context 的實體完成一些工作(如 getResource()),可以直接呼叫 getInstance().getResources() 來完成。
不需要 Context 當作參數傳來傳去。
使用範例
ApplicationEx.getInstance().getResources(); ApplicationEx.getInstance().getFilesDir();
Note 1:
ApplicationEx 並不需要私有化其建構式,e.g.
private ApplicationEx(){
...
}
如果多做這一步反而會產生 IllegalAccessException: access to constructor not allowed 的異常。
因為使用 static 保證只有一個實體被建立,因此這種方法可以確保正確同步化。
Note 2:
經測試無法當做建立Dialog的參數用,e.g.
new Dialog(ApplicationEx.getInstance()); new Dialog(ApplicationEx.getInstance().getApplicationContext());
Dialog建構式的參數必須為 Activity 的 Context