Application概念理解
官方釋義:
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.
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
個人翻譯:
Application類是為了那些需要儲存全域變數設計的基本類。你可以在AndroidManifest.xml的<application>標籤中指定名稱進行自己的實現,這樣的結果是:當你的application或者包被建立的時候將引起那個類被建立。
子類Application通常是沒有必要的。大多數情況下,靜態單例可以通過更加模組化的方式提供相同的功能,如果你的單例需要一個全域的Context(例如註冊一個廣播接收器),當第一次構建單例時,程式內部使用Context.getApplication()方法可以返回一個Context(上下文)。
個人理解:
Application是用來儲存全域變數的,並且是在package建立的時候就跟著存在了。所以當我們需要建立全域變數的時候,直接在Application中去實現。只需要調用Context的getApplicationContext或者Activity的getApplication方法來就可以獲得一個Application對象。
接下來通過例子來看一下具體用法:
GlobalParameterApplication.java
[java]
package com.dt5000.ischool.util;
import android.app.Application;
import com.dt5000.ischool.bean.User;
/**
* @author: duanyr
* @建立時間: 2012-11-14 上午10:50:45
*
* 類說明:全域參數類
*/
public class GlobalParameterApplication extends Application {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
[html] l.activity;
import android.app.Activity;
import com.dt5000.ischool.bean.User;
import com.dt5000.ischool.util.GlobalParameterApplication;
public class UserLoginActivity extends Activity {
@Override
protected void onStart() {
// TODO Auto-generated method stub
User user = new User();
user.setUserName("example");
GlobalParameterApplication gpa = (GlobalParameterApplication) getApplicationContext();
gpa.setUser(user);// 將User資訊放入到Application
gpa.getUser();//取出User資訊
super.onStart();
}
}
AndroidManifest.xml
[html]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dt5000.ischool.activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:maxSdkVersion="15" android:targetSdkVersion="8" />
<application
android:name="com.dt5000.ischool.util.GlobalParameterApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<activity
android:name=".WelcomeActivity"
android:label="@string/title_activity_welcome" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
注意:不用建立<application />,在原有基礎上新增內容:android:name=".your_App_Name"