在Android应用开发的过程中,我们希望在应用程序的所有地方和程序的整个生命周期中都能访问到某些全局变量;或者,在多个Activity的跳转过程中,传递的数据过多,每个Activity进行传递数据情况过多、过于混乱,在这种情况下,我们也可以考虑将传递的数据存储为整个应用的全局变量,在这个时候,我们就可以使用Application类进行全局变量的存储。
Application类中的数据不会应为某个Activity生命周期的结束而消失,它存在于整个应用的生命周期之中。
要实现应用程序级的变量,其主要步骤如下:
1.实现一个类,该类继承自android.app.Application类,并在该类中,封装需要实现的应用程序级全局变量。
public class MyApplication extends Application{
private User user;
private XMPPConnection connection;
private List<User> contacts;
private List<Department> depts;
public void setConnection(XMPPConnection connection){
this.connection=connection;
}
public XMPPConnection getConnection(){
return this.connection;
}
public void setUser(User user){
this.user=user;
}
public User getUser(){
return this.user;
}
public void setContacts(List<User> contacts){
this.contacts=contacts;
}
public List<User> getContacts(){
return contacts;
}
public List<Department> getDepts() {
return depts;
}
public void setDepts(List<Department> depts) {
this.depts = depts;
}
}
2.在应用程序项目的AndroidManifest.xml中,对该application进行配置,如下所示。
上述配置过程与在AndroidManifest.xml文件中添加配置代码效果相同,其代码如下:
<application
android:name="com.example.Application.MyApplication"
........
<application/>
3.完成上述Application类的定义和配置之后,就可以在Activity中对全局变量进行访问和赋值,其实现如下:
((MyApplication)getApplication()).setUser(user);
User valiable=((MyApplication)getApplication()).getUser();
Application对象只有在应用程序中所有Activity都destroy时才会destrory,所有我们可以在任何一个Activity中访问它。(来自百度)