android application 类使用详解
1.什么是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
从描述中可以知道aplication主要用来保存全局的应用程序状态,你可以把全局变量放在这个类里,我的工程里基本都放的是程序的版本号、后台服务器地址、还有一些限制的条件全局常量。
可以通过在AndroidManifest.xml文件的<application>中加入name属性来制定一个应用的名字
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
2.application的继承关系
java.lang.Objectandroid.content.Context
android.content.ContextWrapper
android.app.Application
3.Android程序的入口点
void onConfigurationChanged(Configuration newConfig)
void onCreate() //这里是android程序的真正入口点。
void onLowMemory()
void onTerminate()
Called when the application is starting, before any other application objects 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().
在onCreate里尽量不要放启动时间长的内容,否则会造成程序启动时第一个Activity弹出延时
MyApplication.java
public MyApplication extends Application
{
private static final String VALUE = "My";
private String value;
@Override
public void onCreate()
{
super.onCreate();
setValue(VALUE); // 初始化全局变量
}
public void setValue(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
4.Android Application的获取方式
只需要调用Context的 getApplicationContext或者Activity的getApplication方法来获得一个Application对象,然后再得到相应的成员变量即可。它是代表我们的应用程序的类,使用它可以获得当前应用的主题和资源文件中的内容等,这个类更灵活的一个特性就是可以被我们继承,来添加我们自己的全局属性。