android中application 关于全局变量
转自:http://blog.csdn.net/leilu2008/article/details/6199961
android中application关于全局变量
android编程中,application这样的名词似乎变得那样的不常见,而让大家更为熟悉的是activity、intent、provider、broadcast和service。但其实android中的application也有着它自身的用处。
打开manifest文件,会看到有一个application配置标签,这就是有关application的使用了。那究竟application有什么用处呢?来看看SDK中是如何描述的:
Baseclassforthosewhoneedtomaintainglobalapplicationstate.YoucanprovideyourownimplementationbyspecifyingitsnameinyourAndroidManifest.xml's<application>tag,whichwillcausethatclasstobeinstantiatedforyouwhentheprocessforyourapplication/packageiscreated.
就是说application是用来保存全局变量的,并且是在package创建的时候就跟着存在了。所以当我们需要创建全局变量的时候,不需要再像j2se那样需要创建public权限的static变量,而直接在application中去实现。只需要调用Context的getApplicationContext或者Activity的getApplication方法来获得一个application对象,再做出相应的处理。
因小工程中涉及到的文件比较多,这里就贴代码撒。
application文件:
Java代码
publicclassTestApplicationextendsApplication{
privateintcurIndex;
publicintgetCurIndex(){
returncurIndex;
}
publicvoidsetCurIndex(intcurIndex){
this.curIndex=curIndex;
}
@Override
publicvoidonCreate(){
super.onCreate();
}
@Override
publicvoidonTerminate(){
super.onTerminate();
}
}
application中有一个curIndex和settergetter方法。
第一个acitivty中对application进行的操作:
Java代码
1.TestApplicationapplication=(TestApplication)this.getApplication();
2.Log.i("data",""+application.getCurIndex());
3.application.setCurIndex(5);
TestApplicationapplication=(TestApplication)this.getApplication();
Log.i("data",""+application.getCurIndex());
application.setCurIndex(5);
第二个Activity:
Java代码
1.TestApplicationapplication=(TestApplication)this.getApplication();
2.Log.i("data",""+application.getCurIndex());
3.application.setCurIndex(6);
TestApplicationapplication=(TestApplication)this.getApplication();
Log.i("data",""+application.getCurIndex());
application.setCurIndex(6);
第三个Activity:
Java代码
1.finalTestApplicationapplication=(TestApplication)this.getApplication();
2.Log.i("data",""+application.getCurIndex());
finalTestApplicationapplication=(TestApplication)this.getApplication();
Log.i("data",""+application.getCurIndex());
PS:<applicationandroid:icon="@drawable/icon"android:label="@string/app_name"android:name=".TestApplication">